Prev Next

Appendix B. Annotations

An annotation is a special form of syntactic metadata that can be added to the source code of some programming languages. While PHP has no dedicated language feature for annotating source code, the usage of tags such as @annotation arguments in documentation block has been established in the PHP community to annotate source code. In PHP documentation blocks are reflective: they can be accessed through the Reflection API's getDocComment() method on the function, class, method, and attribute level. Applications such as PHPUnit use this information at runtime to configure their behaviour.

This appendix shows all the varieties of annotations supported by PHPUnit.

@assert

You can use the @assert annotation in the documentation block of a method to automatically generate simple, yet meaningful tests instead of incomplete test cases when using the Skeleton Generator (see Chapter 16):

/**
 * @assert (0, 0) == 0
 */
public function add($a, $b)
{
    return $a + $b;
}

These annotations are transformed into test code such as

/**
 * Generated from @assert (0, 0) == 0.
 */
public function testAdd() {
    $o = new Calculator;
    $this->assertEquals(0, $o->add(0, 0));
}

@author

The @author annotation is an alias for the @group annotation (see the section called “@group) and allows to filter tests based on their authors.

@backupGlobals

The backup and restore operations for global variables can be completely disabled for all tests of a test case class like this

/**
 * @backupGlobals disabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    // ...
}

The @backupGlobals annotation can also be used on the test method level. This allows for a fine-grained configuration of the backup and restore operations:

/**
 * @backupGlobals disabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @backupGlobals enabled
     */
    public function testThatInteractsWithGlobalVariables()
    {
        // ...
    }
}

@backupStaticAttributes

The backup and restore operations for static attributes of classes can be completely disabled for all tests of a test case class like this

/**
 * @backupStaticAttributes disabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    // ...
}

The @backupStaticAttributes annotation can also be used on the test method level. This allows for a fine-grained configuration of the backup and restore operations:

/**
 * @backupStaticAttributes disabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @backupStaticAttributes enabled
     */
    public function testThatInteractsWithStaticAttributes()
    {
        // ...
    }
}

@codeCoverageIgnore*

The @codeCoverageIgnore, @codeCoverageIgnoreStart and @codeCoverageIgnoreEnd annotations can be used to exclude lines of code from the coverage analysis.

For usage see the section called “Ignoring Code Blocks”.

@covers

The @covers annotation can be used in the test code to specify which method(s) a test method wants to test:

/**
 * @covers BankAccount::getBalance
 */
public function testBalanceIsInitiallyZero()
{
    $this->assertEquals(0, $this->ba->getBalance());
}

If provided, only the code coverage information for the specified method(s) will be considered.

Table B.1 shows the syntax of the @covers annotation.

Table B.1. Annotations for specifying which methods are covered by a test

Annotation Description
@covers ClassName::methodName Specifies that the annotated test method covers the specified method.
@covers ClassName Specifies that the annotated test method covers all methods of a given class.
@covers ClassName<extended> Specifies that the annotated test method covers all methods of a given class and its parent class(es) and interface(s).
@covers ClassName::<public> Specifies that the annotated test method covers all public methods of a given class.
@covers ClassName::<protected> Specifies that the annotated test method covers all protected methods of a given class.
@covers ClassName::<private> Specifies that the annotated test method covers all private methods of a given class.
@covers ClassName::<!public> Specifies that the annotated test method covers all methods of a given class that are not public.
@covers ClassName::<!protected> Specifies that the annotated test method covers all methods of a given class that are not protected.
@covers ClassName::<!private> Specifies that the annotated test method covers all methods of a given class that are not private.

@dataProvider

A test method can accept arbitrary arguments. These arguments are to be provided by a data provider method (provider() in Example 4.4). The data provider method to be used is specified using the @dataProvider annotation.

See the section called “Data Providers” for more details.

@depends

PHPUnit supports the declaration of explicit dependencies between test methods. Such dependencies do not define the order in which the test methods are to be executed but they allow the returning of an instance of the test fixture by a producer and passing it to the dependent consumers. Example 4.2 shows how to use the @depends annotation to express dependencies between test methods.

See the section called “Test Dependencies” for more details.

@expectedException

Example 4.7 shows how to use the @expectedException annotation to test whether an exception is thrown inside the tested code.

See the section called “Testing Exceptions” for more details.

@expectedExceptionCode

The @expectedExceptionCode annotation, in conjunction with the @expectedException allows making assertions on the error code of a thrown exception thus being able to narrow down a specific exception.

class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException     MyException
     * @expectedExceptionCode 20
     */
    public function testExceptionHasErrorcode20()
    {
        throw new MyException('Some Message', 20);
    }
}

@expectedExceptionMessage

The @expectedExceptionMessage annotation works similar to @expectedExceptionCode as it lets you make an assertion on the error message of an exception.

class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException        MyException
     * @expectedExceptionMessage Some Message
     */
    public function testExceptionHasRightMessage()
    {
        throw new MyException('Some Message', 20);
    }
}

The expected message can be a substring of the exception Message. This can be useful to only assert that a certain name or parameter that was passed in shows up in the exception and not fixate the whole exception message in the test.

class MyTest extends PHPUnit_Framework_TestCase
{
     /**
      * @expectedException        MyException
      * @expectedExceptionMessage broken
      */
     public function testExceptionHasRightMessage()
     {
         $param = "broken";
         throw new MyException('Invalid parameter "'.$param.'".', 20);
     }
}

@group

A test can be tagged as belonging to one or more groups using the @group annotation like this

class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @group specification
     */
    public function testSomething()
    {
    }

    /**
     * @group regression
     * @group bug2204
     */
    public function testSomethingElse()
    {
    }
}

Tests can be selected for execution based on groups using the --group and --exclude-group switches of the command-line test runner or using the respective directives of the XML configuration file.

@outputBuffering

The @outputBuffering annotation can be used to control PHP's output buffering like this

/**
 * @outputBuffering enabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    // ...
}

The @outputBuffering annotation can also be used on the test method level. This allows for fine-grained control over the output buffering:

/**
 * @outputBuffering disabled
 */
class MyTest extends PHPUnit_Framework_TestCase
{
    /**
     * @outputBuffering enabled
     */
    public function testThatPrintsSomething()
    {
        // ...
    }
}

@runTestsInSeparateProcesses


            

@runInSeparateProcess


            

@test

As an alternative to prefixing your test method names with test, you can use the @test annotation in a method's docblock to mark it as a test method.

/**
 * @test
 */
public function initialBalanceShouldBe0()
{
    $this->assertEquals(0, $this->ba->getBalance());
}

@testdox


            

@ticket


            
Prev Next
1. Automating Tests
2. PHPUnit's Goals
3. Installing PHPUnit
4. Writing Tests for PHPUnit
Test Dependencies
Data Providers
Testing Exceptions
Testing PHP Errors
Testing Output
Assertions
assertArrayHasKey()
assertClassHasAttribute()
assertClassHasStaticAttribute()
assertContains()
assertContainsOnly()
assertCount()
assertEmpty()
assertEqualXMLStructure()
assertEquals()
assertFalse()
assertFileEquals()
assertFileExists()
assertGreaterThan()
assertGreaterThanOrEqual()
assertInstanceOf()
assertInternalType()
assertLessThan()
assertLessThanOrEqual()
assertNull()
assertObjectHasAttribute()
assertRegExp()
assertStringMatchesFormat()
assertStringMatchesFormatFile()
assertSame()
assertSelectCount()
assertSelectEquals()
assertSelectRegExp()
assertStringEndsWith()
assertStringEqualsFile()
assertStringStartsWith()
assertTag()
assertThat()
assertTrue()
assertXmlFileEqualsXmlFile()
assertXmlStringEqualsXmlFile()
assertXmlStringEqualsXmlString()
5. The Command-Line Test Runner
Command-Line switches
6. Fixtures
More setUp() than tearDown()
Variations
Sharing Fixture
Global State
7. Organizing Tests
Composing a Test Suite Using the Filesystem
Composing a Test Suite Using XML Configuration
8. Database Testing
Supported Vendors for Database Testing
Difficulties in Database Testing
The four stages of a database test
1. Clean-Up Database
2. Set up fixture
3–5. Run Test, Verify outcome and Teardown
Configuration of a PHPUnit Database TestCase
Implementing getConnection()
Implementing getDataSet()
What about the Datatabase Schema (DDL)?
Tip: Use your own Abstract Database TestCase
Understanding DataSets and DataTables
Available Implementations
Beware of Foreign Keys
Implementing your own DataSets/DataTables
The Connection API
Database Assertions API
Asserting the Row-Count of a Table
Asserting the State of a Table
Asserting the Result of a Query
Asserting the State of Multiple Tables
Frequently Asked Questions
Will PHPUnit (re-)create the database schema for each test?
Am I required to use PDO in my application for the Database Extension to work?
What can I do, when I get a Too much Connections Error?
How to handle NULL with Flat XML / CSV Datasets?
9. Incomplete and Skipped Tests
Incomplete Tests
Skipping Tests
10. Test Doubles
Stubs
Mock Objects
Stubbing and Mocking Web Services
Mocking the Filesystem
11. Testing Practices
During Development
During Debugging
12. Test-Driven Development
BankAccount Example
13. Behaviour-Driven Development
BowlingGame Example
14. Code Coverage Analysis
Specifying Covered Methods
Ignoring Code Blocks
Including and Excluding Files
Edge cases
15. Other Uses for Tests
Agile Documentation
Cross-Team Tests
16. Skeleton Generator
Generating a Test Case Class Skeleton
Generating a Class Skeleton from a Test Case Class
17. PHPUnit and Selenium
Selenium Server
PHPUnit_Extensions_SeleniumTestCase
18. Logging
Test Results (XML)
Test Results (TAP)
Test Results (JSON)
Code Coverage (XML)
Code Coverage (TEXT)
19. Extending PHPUnit
Subclass PHPUnit_Framework_TestCase
Write custom assertions
Implement PHPUnit_Framework_TestListener
Subclass PHPUnit_Extensions_TestDecorator
Implement PHPUnit_Framework_Test
A. Assertions
B. Annotations
@assert
@author
@backupGlobals
@backupStaticAttributes
@codeCoverageIgnore*
@covers
@dataProvider
@depends
@expectedException
@expectedExceptionCode
@expectedExceptionMessage
@group
@outputBuffering
@runTestsInSeparateProcesses
@runInSeparateProcess
@test
@testdox
@ticket
C. The XML Configuration File
PHPUnit
Test Suites
Groups
Including and Excluding Files for Code Coverage
Logging
Test Listeners
Setting PHP INI settings, Constants and Global Variables
Configuring Browsers for Selenium RC
D. Index
E. Bibliography
F. Copyright