简体   繁体   English

PHPUnit:为自定义断言编写测试

[英]PHPUnit: Writing tests for custom assertions

For our PHPUnit testing, we sometimes write custom assertions. 对于我们的PHPUnit测试,有时我们会编写自定义断言。 Today I found a custom assertion that wasn't asserting quite what it ought to have been. 今天,我发现了一个自定义断言,该断言并没有完全断定应有的样子。 It seems that this problem could have been avoided if I had written a unit test for the assertion itself. 如果我为断言本身编写了单元测试,似乎可以避免这个问题。

The only problem I see is that I'm not quite sure how to handle writing tests for an assertion that it ought to fail, without having that lead to the test itself failing. 我看到的唯一问题是,我不确定如何处理应该断言的断言,而不会导致测试本身失败。 In other words, for a test that expects a string, 'foo', I want to do something like: 换句话说,对于需要字符串'foo'的测试,我想执行以下操作:

public function testAssertFoo()
{
   $var = 'bar';
   $callable = array( $this, "assertFoo" );
   $this->assertTestFails( $callable, $var );
}

Of course, there is no assertTestFails assertion. 当然,没有assertTestFails断言。 But is there a clean way to do something like that? 但是,有没有一种干净的方法来做类似的事情?

Assuming that assertFoo uses PHPUnit's built-in assertions such as assertEquals , you can simply catch the PHPUnit_Framework_ExpectationFailedException that is thrown when the assertion fails. 假设assertFoo使用PHPUnit的内置断言(例如assertEquals ,您可以简单地捕获断言失败时抛出的PHPUnit_Framework_ExpectationFailedException

function testAssertFoo() {
    try {
        $this->assertFoo('bar');
        self::fail("assertFoo should fail for 'bar'");
    }
    catch (PHPUnit_Framework_ExpectationFailedException $e) { /* test passed */ }
}

function assertFoo($value) {
    self::assertEquals('foo', $value);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM