Better PHPUnit Group Annotations

  • Posted by Mike Naberezny in PHP,Testing

    Last week, Sebastian Bergmann wrote about the new support for TestNG-style grouping of tests in the upcoming PHPUnit 3.2. This feature allows individual test methods to be grouped with an @group annotation.

    I typically organize my test case classes into high-level groups such as unit and functional. Method-level group annotations are inconvenient for us because we’d need to annotate every method of every test case class.

    I was discussing this with Sebastian and not long after he had committed changesets 1293 and 1294 to the PHPUnit repository.

    Now, @group annotations on the class inherit to all the methods of that class. When all the test methods of a class belong to the same group, just annotate the class:

    /**
     * @group functional
     */
    class FooTest extends PHPUnit_Framework_TestCase {
    ...

    With that one annotation to the class, a command like this one will run all the tests in the class above and any other tests annotated with @group functional:

    $ phpunit --group functional AllTests.php

    That’s a great shortcut. It shouldn’t take long to put @group annotations on the test case classes of a project.

    Having the ability to annotate individual test methods is still very useful because test methods (and even classes) may belong to multiple groups.

    Sebastian pointed out a great use case for this in the form of testing bugs that span multiple test case classes. I was already commenting my tests with bug tracker numbers, now I’ve just converted them to @group annotations.

    Whenever we receive a bug report from a client, we will create tests to reproduce the bug and then fix the implementation so the tests pass. This ensures that the bug can be reproduced and that we won’t repeat the same mistake again later.

    Now, the test methods associated with a bug can be annotated like @group bug42. Running phpunit --group bug42 AllTests.php will run only the tests associated with bug #42, regardless of what files and groups those test methods span.

    PHPUnit 3.2 is looking great.

Post a comment


Thanks for commenting. Please remember to be nice to others and keep your comment relevant to the discussion. I reserve the right to remove comments that don't meet these simple guidelines.