PHPUnit自定义断言消息

时间:2015-12-01 17:22:16

标签: php phpunit

我正在编写一个与PHPUnit一起使用的自定义断言,但每当我放置一个自定义断言时,我都会看到两(2)条错误消息。

代码:

$this->_testCase->assertThat(
    $hasMessageCode,
    $this->_testCase->isTrue(),
   "Failed asserting that API response contains a message whose code is {$code}."
);

输出:

1) ApiTest::testFoo
Failed asserting that API response contains an error whose code is REG012.
Failed asserting that false is true.

有什么方法我只能输出自定义消息并跳过第二个消息?

1 个答案:

答案 0 :(得分:0)

我假设PHPUnit立即评估测试然后输出,如果它创建了某种类型的列表,后来对其进行了评估,则可能无法正常工作。不是最干净的解决方案,但是您可能会弄乱输出缓冲区。

public function whateverFunctionYouHave($hasMessageCode) {
  ob_start();
  $this->_testCase->assertThat(
    $hasMessageCode,
    $this->_testCase->isTrue(),
   "Failed asserting that API response contains a message whose code is {$code}."
  );
  $out = ob_get_contents();
  ob_end_clean();
  $expectedDefaultMessage = "Failed asserting that false is true.";
  if (strpos($out, $expectedDefaultMessage) !== false) {
    $out = str_replace($expectedDefaultMessage, "");
    echo $out; 
  }
}

聚会晚了一点,但是...应该起作用。