PHPUnit:如何为扩展异常测试创建自定义注解


PHPUnit: how to create custom annotations for extended exception tests

我希望能够编写使用自定义注释来确定测试是通过还是失败的测试。

我在代码中使用了自定义异常,它将getter方法添加到Exception基类中。例如:

class MyException extends Exception
{
    // ...
    public function getFoo()
    {
        //...
    }
}

,我希望能够编写一个测试,测试foo是给定值,像这样:

class BarTest extends PHPUnit_Framework_TestCase {
    /**
     * @expectedException MyException
     * @expectedExceptionFoo 'baz'
     */
    public function testBarThrowsMyExceptionWithFooEqualsBaz()
    {
        $bar = new Bar();
        $bar->throwExceptionWithFooEqualsBaz();
    }
}

此刻,我正在研究一个解决方案,涉及扩展PHPUnit_Framework_TestCase,覆盖runTest(),但它变得非常复杂,因为runTest()使用了这么多私有方法和类变量,我不得不重写超过一半的类(大约1200行)。有更简单的方法吗?

一个更简单的解决方案的提示是PHPUnit_Framework_TestCase具有以下可能有用的方法:

  • public function setUseErrorHandler($useErrorHandler)
  • protected function setUseErrorHandlerFromAnnotation()
  • protected function setExpectedExceptionFromAnnotation()

但是我一直在浏览PHPUnit的代码,看看我如何使用它们,有这么多的间接和这么少的注释,现在看起来像更难的选择?

这可能是一个起点:

https://codesymphony.co/creating-your-own-phpunit-requires-annotations/

它描述了如何实现自定义@requires注释,但是代码可以用作实现任何自定义注释的起点。