在PhpUnit数据提供者中使用标签的例子

99 阅读1分钟

如果你想看到带有标签的合理的错误信息,用于使用数据提供者的破碎单元测试,你可以按照下面的第二个测试案例。检查 "测试结果 "部分的差异。

没有标签的数据提供者

class SomethingTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     *
     * @dataProvider getDataProvider
     */
    public function it_does_something(
        $param1,
        $param2
    ) {
        // ...
    }

    public function getDataProvider()
    {
        return [
            ['Hello', 11],
            ['World', 22],
        ];
    }
}

测试结果

1) SomethingTest::it_does_something with data set #0 ('Hello', 11)
Failed asserting that false matches expected true.
2) SomethingTest::it_does_something with data set #1 ('World', 22)
Failed asserting that false matches expected true.

带标签的数据提供者

class SomethingTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     *
     * @dataProvider getDataProvider
     */
    public function it_does_something(
        $param1,
        $param2
    ) {
        // ...
    }

    public function getDataProvider()
    {
        return [
            'Testing Hello message' => [
              '$param1' => 'Hello',
              '$param2' => 11
            ],
            'Testing World message' => [
              '$param1' => 'World',
              '$param2' => 22
            ],
        ];
    }
}

测试结果

1) SomethingTest::it_does_something with data set "Testing Hello message" ('Hello', 11)
Failed asserting that false matches expected true.
2) SomethingTest::it_does_something with data set "Testing World message" ('World', 22)
Failed asserting that false matches expected true.