如何运行带有依赖项的PHPUnit测试

4

我的设置如下:

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
}

我想专注于testTwo,但当我执行phpunit --filter testTwo时,我会收到以下信息:

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

我的问题:是否有一种方法可以运行一个测试及其所有依赖项?

3个回答

3
我知道,这也不是很方便,但你可以试试。
phpunit --filter 'testOne|testTwo' 

根据phpunit文档,我们可以使用正则表达式作为过滤器。
此外,您可以考虑使用数据提供程序来生成第二个测试的值。但请注意,数据提供程序方法将始终在所有测试之前执行,因此如果有任何繁重的处理,它可能会减慢执行速度。
另一种方法是创建一些辅助方法或对象来执行某些实际工作并缓存结果以供不同的测试使用。然后,您将不需要使用依赖项,并且您的数据将在请求时生成并缓存以供不同的测试共享。
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
}

只是一个提醒,我们在Windows PowerShell上使用了两个管道符号:phpunit --filter 'testOne||testTwo'。 - Ondrej

3

没有一种开箱即用的方式来自动运行所有依赖项。但是,您可以使用@group注释将测试分组,然后运行phpunit --group myGroup


1
更可惜的是,没有简单的方法来做到这一点!组可以工作,但需要与您经常想要测试的路径一样多的组 - 最终在 n 组中产生重要的依赖关系,其中 n 是依赖测试的数量。这很混乱,应该有更简单的方法!我已经提出了一个建议。 (https://github.com/sebastianbergmann/phpunit/issues/2166) - artfulrobot

2

使用正则表达式

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

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