【问题标题】:Running a PHPUnit testcase multiple times多次运行 PHPUnit 测试用例
【发布时间】:2013-08-17 16:30:13
【问题描述】:

我正在寻找一种如何使用不同设置多次运行测试用例的方法。

我正在测试一个数据库访问类(数十种测试方法),并希望在“正常模式”和“调试模式”下对其进行测试。两种模式必须产生相同的测试结果。

在测试用例设置中是否有可能做到这一点?还是重写 run() 方法? 当然,我不想写两次测试:)

谢谢

编辑:明白了!

public function run(PHPUnit_Framework_TestResult $result = NULL)
{
    if ($result === NULL) {
        $result = $this->createResult();
    }

    /**
     * Run the testsuite multiple times with different debug level
     */
    $this->debugLevel = 0;
    print "Setting debug level to: " . $this->debugLevel . PHP_EOL;
    $result->run($this);

    $this->debugLevel = 8;
    print "Setting debug level to: " . $this->debugLevel . PHP_EOL;
    $result->run($this);

    $this->debugLevel = 16;
    print "Setting debug level to: " . $this->debugLevel . PHP_EOL;
    $result->run($this);

    return $result;
}

public function setUp()
{
    parent::setUp();
    $this->myclass->setOptions('debug', $this->debugLevel);
}

【问题讨论】:

  • 看看@dataProvider 发出测试数据集的函数。
  • 我知道 dataProviders 的用法 :) 我只想更改类的一个简单设置,然后再次运行所有测试方法。类似的东西:运行(); $class->setDebug(true);运行();
  • 您可以将所有代码移动到抽象测试用例中,并在 setUp() 中使用不同的代码创建 2 个子级。
  • 太棒了!不过,您应该为每次迭代(但第一次)运行 setUp() 以实现隔离。
  • 仅供参考,您应该将 count() 设置为 3,因为您要运行 3 次测试。

标签: php phpunit testcase


【解决方案1】:

我认为斯文的答案是正确的。写下你要设置的内容,并给出你需要的测试用例参数,比如:

/**
 * @dataProvider forMyTest
 */
public function testWithDifferentDbType($type, $param1, $param ....)
{
    $this->assertExists(....);
}

public function forMyTest() {
    return [
        [
            true
            [$prodDb, $param1, $param, .....],
        ],
        [   
            false,
            [$debugDb, $param1 $param, ....,

        ],
    ];
}

【讨论】:

【解决方案2】:

PHPUnit 提供测试装饰器。 documentation 实际上有重复装饰器作为如何处理装饰器的示例。装饰器将以可重用的方式实现行为的完美方式,而不依赖于子类化PHPUnit_Framework_TestCase

【讨论】:

    【解决方案3】:

    您可以在单元测试中创建多个方法。它们都将运行,每个测试方法运行后都会调用setUp 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-10
      • 2017-08-09
      • 2015-06-15
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      • 2019-10-05
      • 1970-01-01
      相关资源
      最近更新 更多