PHPUnit数据提供程序动态创建

3

我有一个关于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之前运行。

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

1个回答

0

我只有静态字段的想法(也许不是最好的,但如果有更好的,我会考虑)。

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]
    ];
}

你必须记住,该字段在所有类中都可见,因此如果您想使用另一个数据集,则必须将该字段置空。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接