PHPUnit - 断言失败但我想继续测试

hel*_*boy 14 php phpunit unit-testing

->assertTrue(false);
->assertTrue(true);
Run Code Online (Sandbox Code Playgroud)

第一个断言失败,执行停止.但我想继续进一步的代码片段.

是否有可能在PHPUnit中

Ben*_*ird 13

其他的回答是正确的 - 如果你想要能够做到这一点,你真的应该将你的断言分成单独的测试.但是,假设你有合理的理由想要这样做......有一种方法.

Phpunit断言失败实际上是异常,这意味着您可以自己捕获并抛出它们.例如,尝试此测试:

public function testDemo()
{
    $failures = [];
    try {
        $this->assertTrue(false);
    } catch(PHPUnit_Framework_ExpectationFailedException $e) {
        $failures[] = $e->getMessage();
    }
    try {
        $this->assertTrue(false);
    } catch(PHPUnit_Framework_ExpectationFailedException $e) {
        $failures[] = $e->getMessage();
    }
    if(!empty($failures))
    {
        throw new PHPUnit_Framework_ExpectationFailedException (
            count($failures)." assertions failed:\n\t".implode("\n\t", $failures)
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,它会尝试两个断言,这两个断言都会失败,但它会等到最后将所有失败输出消息作为单个异常抛出.

  • 现在的异常类是 `PHPUnit\Framework\ExpectationFailedException`,但其余的仍然有效:) (2认同)

Ste*_*eve 10

你可以把失败存储到最后,比如说

$passing = true;
if (! false) { $passing = false; }
if (! true) { $passing = false; }
$this->assertTrue($passing);
Run Code Online (Sandbox Code Playgroud)

但我强烈反对这种形式的测试.我写了这样的测试,并且它们指数地失控,更糟糕的是,由于难以找到的原因,你开始出现奇怪的失败.

另外,比我更聪明的人同意,测试不应该有任何条件(if/else,try/catch),因为每个条件都会增加测试的复杂性.如果需要条件,则可能需要非常仔细地查看测试和SUT或系统测试,以便使其更简单.

更好的方法是将其更改为两个测试,如果它们共享设置的重要部分,则将这两个测试移动到新的测试类中,并在Setup()方法中执行共享设置.


Dan*_*ite 7

这打破了单元测试的重点.您可能希望将其分解为更多的测试方法,而不是使用单片测试方法.

这是一些伪代码,作为一个坏例子.

MyBadTestMethod()
{
   someResult = MyMethod();
   assertIsCorrect(someResult);
   myResult2 = MyMethod2(someResult);
   assertIsCorrect(myResult2);
}
Run Code Online (Sandbox Code Playgroud)

MyMethod2myResult2将失败.

这是一个更好的例子.

MyTestMethod1()
{
   someResult = MyMethod();
   assertIsCorrect(someResult);
}
MyTestMethod2()
{
   myResult2 = MyMethod2(someCorrectResult);
   assertIsCorrect(myResult2);
}
Run Code Online (Sandbox Code Playgroud)


Ous*_*bel 5

我迟到了,但我建议使用测试套件的配置文件来轻松实现这一点。

您可以phpunit.xml从运行 phpunit 测试的位置创建文件。因此 phpunit 将运行那里列出的所需测试。

PHPUnit 3.7.38 由 Sebastian Bergmann 编写。

从 /path/phpunit.xml 读取配置

在该文件中,您可以指定您不想在失败时停止。

<phpunit bootstrap="vendor/autoload.php" stopOnFailure="false">
  <testsuites>
    <testsuite name="Test">
      <file>tests/ClassTest.php</file>
    </testsuite>
  </testsuites>
</phpunit>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 这似乎只适用于整个测试套件。来自文档:_此属性配置在第一个测试完成且状态为“失败”后是否应停止测试套件执行_ https://phpunit.readthedocs.io/en/9.5/configuration.html (2认同)