【问题标题】:How to test that PHPUnit_Framework_TestCase fails when an expected exception is not produced当没有产生预期的异常时如何测试 PHPUnit_Framework_TestCase 失败
【发布时间】:2016-01-18 00:26:50
【问题描述】:

我正在尝试扩展 PHPUnit 的功能。

我想扩展它关于它如何允许测试断言预期的Exception 被抛出的行为。

我通过扩展PHPUnit_Framework_TestCase 来做到这一点,如下所示:

class Improved_TestCase extends PHPUnit_Framework_TestCase {
    //...
}

问题是,我现在需要编写一个测试,表明如果不抛出 @expectedException,测试将失败。

例如,我想证明以下测试会失败:

/**
 * I want to write a TestTest that passes when these tests would fail
 */
class FooTest extends Improved_TestCase {

    /**
     * @expectedException Exception
     */
    function testFooThrowsAnnotatedException()
    {
        Foo::thisWillNotThrowAnException();
    }

    function testFooThrowsSetException()
    {
        $this->setExpectedException('Exception');

        Foo::thisWillNotThrowAnException();
    }

}

上述测试应该失败。但是有些我需要编写一个在上述测试失败时会通过的测试

我已尝试查看PHPUnit's tests source code,但我不明白它如何或在何处测试预期异常测试的工作情况。

据我所知,我最好的猜测是@expectedException behaviour is tested here,但这没有意义,因为如果 PHPUnit 工作正常,这些测试将失败

【问题讨论】:

    标签: unit-testing exception phpunit


    【解决方案1】:

    测试它的代码是here in TestCaseTest.php:

    function testException()
    {
        $test = new ThrowExceptionTestCase('test');
        $test->setExpectedException('RuntimeException');
    
        $result = $test->run();
    
        $this->assertEquals(1, count($result));
        $this->assertTrue($result->wasSuccessful());
    }    
    
    public function testNoException()
    {
        $test = new ThrowNoExceptionTestCase('test');
        $test->setExpectedException('RuntimeException');
    
        $result = $test->run();
    
        $this->assertEquals(1, $result->failureCount());
        $this->assertEquals(1, count($result));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2015-12-27
      • 2017-10-28
      相关资源
      最近更新 更多