【问题标题】:PHPUnit data provider dynamically creationPHPUnit 数据提供者动态创建
【发布时间】:2015-08-12 07:50:47
【问题描述】:

我有一个关于 PHPUnit 数据提供者的非常有趣的问题。

protected $controller;

protected function setUp()
{
    $this->controller = new ProductController(); 
}

 /**
 * @covers       ProductsController::createItem
 * @dataProvider getTestDataProvider
 * @param number $name
 */
public function testCreateItem($name)
{   
    $prod = $this->controller->createItem($name);
    $id = $prod->getId;
    $this->assertInternalType('int', $id);
    $this->assertInstanceOf('Product', $prod);
}

/**
 * @covers           ProductsController::getItemInfo
 * @depends          testCreateItem
 * @param number $id
 */
public function testGetItemInfo($id)
{
    $info = $this->controller->getItemInfo($id);
    $this->assertArrayHasKey('id',$info);
    $this->assertEquals($id, $info['id']);
}

我使用getTestDataProvider 从 CSV 文件中获取测试数据。然后testCreateItem 从 CSV 行创建 10 个新产品。

如何创建一个包含$id 新产品的数组并将其用作testGetItemInfo 的数据提供者?我无法将其存储在 SESSION 或文件中,因为提供程序函数在 SetUp 之前运行。

也许有人已经遇到过类似的问题?

【问题讨论】:

    标签: php phpunit automated-tests


    【解决方案1】:

    我只有静态领域的想法(也许不是最好的,但如果有人有更好的我会看看)。

    private static $ids;
    
    /**
     * @dataProvider some
     */
    public function testT1($id)
    {
        self::$ids[] = $id;
    }
    
    /**
     * @depends testT1
     */
    public function testT2()
    {
        var_dump(self::$ids);
    }
    
    public function some()
    {
        return [
            [1],
            [2],
            [3]
        ];
    }
    

    您必须记住该字段在所有类中都是可见的,因此如果您想使用另一个数据集,您必须取消该字段。

    【讨论】:

      猜你喜欢
      • 2011-10-21
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      • 2018-05-17
      • 2014-11-19
      • 2013-02-14
      • 2017-03-16
      • 1970-01-01
      相关资源
      最近更新 更多