Annotation Cheet sheet

Laravel Test PHPUnit Annotation Cheet sheet

Organizing Test

@author

Allows to filter tests based on their authors.

/**
 * @author KJ
 */
public function testSomething() {
    // ...
}

@group

Specify the group in your phpunit.xml file or running command.

/**
 * @group first
 */
public function testFirstThing() {
    // ...
}

/**
 * @group second
 * @group other_group
 */
public function testSecondThing() {
    // ...
}

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

vendor/bin/phpunit --group first --group second

@ticket

The @ticket annotation is an alias for the @group annotation and allows to filter tests based on their ticket ID.

/**
 * @ticket ticket_123
 */
public function testSomething() {
    // ...
}

@test

As an alternative to prefixing your test method names with test

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

@testdox

Specifies an alternative description used when generating the agile documentation sentences.

/**
 * @testdox A bank account
 */
final class BankAccountTest extends TestCase
{
    /**
     * @testdox has an initial balance of zero
     */
    public function balanceIsInitiallyZero(): void
    {
        $this->assertSame(0, $this->ba->getBalance());
    }
}

Using the @testdox annotation at method level with a @dataProvider

/**
 * @dataProvider additionProvider
 * @testdox Adding $a to $b results in $expected
 */
public function testAdd($a, $b, $expected)
{
    $this->assertSame($expected, $a + $b);
}

public function additionProvider()
{
    return [
        'data set 1' => [0, 0, 0],
        'data set 2' => [0, 1, 1],
        'data set 3' => [1, 0, 1],
        'data set 4' => [1, 1, 3]
    ];
}

@after

Specify methods that should be called after each test method in a test case class.

final class MyTest extends TestCase
{
    /**
     * @after
     */
    public function tearDownSomeFixtures(): void
    {
        // ...
    }

    /**
     * @after
     */
    public function tearDownSomeOtherFixtures(): void
    {
        // ...
    }
}

@afterClass

Specify static methods that should be called after all test methods in a test class have been run to clean up shared fixtures.

final class MyTest extends TestCase
{
    /**
     * @afterClass
     */
    public static function tearDownSomeSharedFixtures(): void
    {
        // ...
    }

    /**
     * @afterClass
     */
    public static function tearDownSomeOtherSharedFixtures(): void
    {
        // ...
    }
}

@before

Specify methods that should be called before each test method in a test case class.


final class MyTest extends TestCase
{
    /**
     * @before
     */
    public function setupSomeFixtures(): void
    {
        // ...
    }

    /**
     * @before
     */
    public function setupSomeOtherFixtures(): void
    {
        // ...
    }
}

@beforeClass

Specify static methods that should be called before any test methods in a test class are run to set up shared fixtures.

final class MyTest extends TestCase
{
    /**
     * @beforeClass
     */
    public static function setUpSomeSharedFixtures(): void
    {
        // ...
    }

    /**
     * @beforeClass
     */
    public static function setUpSomeOtherSharedFixtures(): void
    {
        // ...
    }
}

@backupGlobals

PHPUnit can optionally backup all global and super-global variables before each test and restore this backup after each test.

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

    /**
     * @backupGlobals disabled
     */
    public function testThatDoesNotInteractWithGlobalVariables(): void
    {
        // ...
    }
}

@backupStaticAttributes

PHPUnit can optionally backup all static attributes in all declared classes before each test and restore this backup after each test.

  • @backupStaticAttributes enabled
  • @backupStaticAttributes disabled
/**
 * @backupStaticAttributes enabled
 */
class MyTest extends TestCase
{
    public function testThatInteractsWithStaticAttributes(): void
    {
        // ...
    }

    /**
     * @backupStaticAttributes disabled
     */
    public function testThatDoesNotInteractWithStaticAttributes(): void
    {
        // ...
    }
}

@doesNotPerformAssertions

Prevents a test that performs no assertions from being considered risky.

@preserveGlobalState

PHPUnit will attempt to preserve the global state from the parent process by serializing all globals in the parent process and unserializing them in the child process

This can cause problems if the parent process contains globals that are not serializable. To fix this, you can prevent PHPUnit from preserving global state with the @preserveGlobalState annotation.

final class MyTest extends TestCase
{
    /**
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
    public function testInSeparateProcess(): void
    {
        // ...
    }
}

@runTestsInSeparateProcesses

Indicates that all tests in a test class should be run in a separate PHP process.

/**
 * @runTestsInSeparateProcesses
 */
final class MyTest extends TestCase
{
    // ...
}

@runInSeparateProcess

Indicates that test method should be run in a separate PHP process.

final class MyTest extends TestCase
{
    /**
     * @runInSeparateProcess
     */
    public function testInSeparateProcess(): void
    {
        // ...
    }
}

Data

@dataProvider

The data provider method to be used is specified using the @dataProvider annotation.

final class DataTest extends TestCase
{
    /**
     * @dataProvider additionProvider
     */
    public function testAdd(int $a, int $b, int $expected): void
    {
        $this->assertSame($expected, $a + $b);
    }

    public function additionProvider(): array
    {
        return [
            [0, 0, 0],
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 3]
        ];
    }
}

@depends

Declaration of explicit dependencies between test methods

final class StackTest extends TestCase
{
    public function testEmpty(): array
    {
        $stack = [];
        $this->assertEmpty($stack);

        return $stack;
    }

    /**
     * @depends testEmpty
     */
    public function testPush(array $stack): array
    {
        array_push($stack, 'foo');
        $this->assertSame('foo', $stack[count($stack)-1]);
        $this->assertNotEmpty($stack);

        return $stack;
    }

    /**
     * @depends testPush
     */
    public function testPop(array $stack): void
    {
        $this->assertSame('foo', array_pop($stack));
        $this->assertEmpty($stack);
    }
}

@testWith

Instead of implementing a method for use with @dataProvider, you can define a data set using the @testWith annotation.

/**
 * @testWith ["test", 4]
 *           ["longer-string", 13]
 */
public function testStringLength(string $input, int $expectedLength): void
{
    $this->assertSame($expectedLength, strlen($input));
}

An object representation in JSON will be converted into an associative array.

/**
 * @testWith [{"day": "monday", "conditions": "sunny"}, ["day", "conditions"]]
 */
public function testArrayKeys(array $array, array $keys): void
{
    $this->assertSame($keys, array_keys($array));
}

Code Coverage

@codeCoverageIgnore

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

@covers

Specify which parts of the code it is supposed to test:

/**
 * @covers \BankAccount
 */
public function testBalanceIsInitiallyZero(): void
{
    $this->assertSame(0, $this->ba->getBalance());
}
Annotation Recommended Description
@covers ClassName V Specifies that the annotated test method covers all methods of a given class.
@covers ::functionName V Specifies that the annotated test method covers the specified global function.
@covers ClassName::methodName X Specifies that the annotated test method covers the specified method.
@covers ClassName X Specifies that the annotated test method covers all methods of a given class and its parent class(es).
@covers ClassName:: X Specifies that the annotated test method covers all public methods of a given class.
@covers ClassName:: X Specifies that the annotated test method covers all protected methods of a given class.
@covers ClassName:: X Specifies that the annotated test method covers all private methods of a given class.
@covers ClassName::<!public> X Specifies that the annotated test method covers all methods of a given class that are not public.
@covers ClassName::<!protected> X Specifies that the annotated test method covers all methods of a given class that are not protected.
@covers ClassName::<!private> X Specifies that the annotated test method covers all methods of a given class that are not private.

@coversNothing

Specify that no code coverage information will be recorded for the annotated test case.

Others

@requires

Skip tests when common preconditions, like the PHP Version or installed extensions, are not met.

Type Possible Values Examples Another example
PHP Any PHP version identifier along with an optional operator @requires PHP 7.1.20 @requires PHP >= 7.2
PHPUnit Any PHPUnit version identifier along with an optional operator @requires PHPUnit 7.3.1 @requires PHPUnit < 8
OS A regexp matching PHP_OS @requires OS Linux @requires OS WIN32|WINNT
OSFAMILY Any OS family @requires OSFAMILY Solaris @requires OSFAMILY Windows
function Any valid parameter to function_exists @requires function imap_open @requires function ReflectionMethod::setAccessible
extension Any extension name along with an optional version identifier and optional operator @requires extension mysqli @requires extension redis >= 2.2.0

The following operators are supported for PHP, PHPUnit, and extension version constraints: <, <=, >, >=, =, ==, !=, <>.

/**
 * @requires extension mysqli
 */
final class DatabaseTest extends TestCase
{
    /**
     * @requires PHP >= 5.3
     */
    public function testConnection(): void
    {
        // Test requires the mysqli extension and PHP >= 5.3
    }

    // ... All other tests require the mysqli extension
}

@large

The @large annotation is an alias for @group large.

A large test will fail if it takes longer than 60 seconds to execute.

This timeout is configurable via the timeoutForLargeTests attribute in the XML configuration file.

@medium

The @medium annotation is an alias for @group medium. A medium test must NOT depend on a test marked as @large.

A medium test will fail if it takes longer than 10 seconds to execute.

This timeout is configurable via the timeoutForMediumTests attribute in the XML configuration file.

@small

The @small annotation is an alias for @group small. A small test must NOT depend on a test marked as @medium or @large.

A small test will fail if it takes longer than 1 second to execute.

This timeout is configurable via the timeoutForSmallTests attribute in the XML configuration file.

Reference