如何运行PHPUnit测试及其依赖关系


How to run PHPUnit test with its dependencies

我的设置是这样的:

class MyTest extends PHPUnit_Framework_TestCase
{
    // More tests before
    public function testOne()
    {
        // Assertions
        return $value;
    }
    /**
     * @depends testOne
     */
    public function testTwo($value)
    {
        // Assertions
    }
    // More tests after
}

我想专注于测试二,但当我做phpunit --filter testTwo时,我会收到这样的消息:

This test depends on "MyTest::testOne" to pass.
No tests executed!

我的问题是:有没有一种方法可以运行一个包含所有依赖项的测试?

没有现成的方法可以自动运行所有依赖项。但是,您可以使用@group注释将测试分组,然后运行phpunit --group myGroup

我知道,这也不太方便,但你可以试试

phpunit --filter 'testOne|testTwo' 

根据phpunit文档,我们可以使用regexp作为过滤器。

此外,您可以考虑使用数据提供程序为第二次测试生成值。但请注意,数据提供程序方法总是在所有测试之前执行,所以如果处理量很大,它可能会减慢执行速度。

还有一种方法是创建一些辅助方法或对象,这些方法或对象将执行一些实际工作并缓存结果以供各种测试使用。然后,您将不需要使用依赖项,并且您的数据将根据请求生成并缓存以供不同的测试共享。

class MyTest extends PHPUnit_Framework_TestCase
{
    protected function _helper($someParameter) {
        static $resultsCache;
        if(!isset($resultsCache[$someParameter])) {
            // generate your $value based on parameters
            $resultsCache[$someParameter] = $value;
        }
        return $resultsCache[$someParameter];
    }
    // More tests before
    public function testOne()
    {
        $value = $this->_helper('my parameter');
        // Assertions for $value
    }
    /**
     * 
     */
    public function testTwo()
    {
        $value = $this->_helper('my parameter');
        // Get another results using $value
        // Assertions
    }
    // More tests after
}

使用正则表达式

phpunit --filter='/testOne|testTwo/'