phpunit可以使用多个数据提供者吗

2022-01-25 00:00:00 unit-testing tdd php phpunit

简而言之:phpunit在运行测试时可以使用多个数据提供者吗?

One question in short: can phpunit use multiple data provider when running test?

例如,我有一个名为 getById 的方法,我需要为它运行成功和不成功的测试用例.

For example, I have a method called getById, and I need to run both successful and unsuccessful testcases for it.

成功的测试用例意味着它可以返回相应的记录.而对于不成功的,输入可以分为两类:无效和失败.

The successful testcases means that it can return a corresponding record. And for the unsuccessful, the input can fall in two categories: invalid and failed.

invalid表示输入不合法,failed表示输入可能有效,但没有对应的ID对应的记录.

The invalid means that the input is not legal, while failed means the input could be valid, but there is no corresponding record with that ID.

所以代码是这样的:

/** 
 * @dataProvider provideInvalidId
 * @dataProvider provideFailedId
 */
public function testGetByIdUnsuccess($id)
{   
    $this->assertNull($this->model->getById($id));
}   

但事实证明,只使用了第一个数据提供者,而忽略了第二个.虽然我不确定这种情况是否常见,但这是问题所在.我们可以使用多个数据提供者吗?如果可以,怎么做?

But it turned out that only the first data provider has been used, ignoring the second one. Though I am not sure this senario is common or not, but here is the question. Can we use multiple data provider? And if we can, how?

PS:在 这里

推荐答案

只是问题的更新,一个 拉取请求已被接受,现在代码:

Just an update to the question, a pull request was accepted and now the code:

/** 
 * @dataProvider provideInvalidId
 * @dataProvider provideFailedId
 */
public function testGetByIdUnsuccess($id)
{   
    $this->assertNull($this->model->getById($id));
}

将在 PHPUnit 5.7 上工作,您可以添加任意数量的提供程序.

Will work on PHPUnit 5.7, you'll be able to add as many providers as you want.

相关文章