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

I want to be able to write tests which use a custom annotation to determine whether a test has passed or failed.

I use custom exceptions in my code, which add a getter method to the base Exception class. for example:

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

and I want to be able to write a test which tests that foo is of a given value, like so:

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

At the moment I'm working on a solution which involves extending PHPUnit_Framework_TestCase, that overrides runTest() but it is becoming ridiculously complicated, since runTest() uses so many private methods and class variables, I'm having to rewrite over half the class (some 1200 lines). Is there a simpler way?

One hint at a simpler solution is that PHPUnit_Framework_TestCase has the following methods which might be useful:

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

but I have been trawling through PHPUnit's code to see how I might use them and there is so much indirection with so few comments that right now it's looking like the harder option?

This may be a starting point:

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

It describes how to implement custom @requires annotations, but the code can be used as a jumping point to implement any custom annotation.