简体   繁体   中英

How to document PHPUnit tests

I'm writing a lot of unit tests and I'm afraid one day I'll come back to read the test codes and not be able to understand what's being tested.

The question is: How do i document PHPUnit tests using PHPDoc ?

Use the @covers annotation (it's specific to PHPUnit, not a documentation tag used by phpDocumentor) to highlight what the test case is supposed to exercise. By having it in the docblock, you tell the code reader what code is targeted by the test. If you have phpDocumentor also generating docs for your test cases, then it should treat the annotation as a "custom tag", and show it as generic information. Note, though, that the point of @covers is to limit the code coverage measurements done by PHPUnit. Its use as doc info is incidental, but useful.

If you want some kind of document linking between the test case and the tested code, also put the @uses tag in the test case's docblock. That should result in @used-by tag automatically appearing in the documentation for the tested method/function.

One way as suggested is to use the test function name but this can end up too abbreviated and cryptic. In this case put some text in the optional $message parameter to explain what the test is doing.

assertSame(mixed $expected, mixed $actual[, string $message = ''])

I finds this helps, particularly if you are used to writing JavaScript tests with something like Jasmine where you put a human readable sentence to explain what is being tested for each test.

Here is a simple example. If you put the test description as the default value for a function argument it will be documented. If you put just one test per function (ie single responsibility principle) then when you look back in a few years time maybe the tests will make more sense than having multiple tests per function.

<?php
use PHPUnit\Framework\TestCase;

final class ArrayPushTest extends TestCase
{
    public function testPushStringToEmptyArray(string $description = 
        'A string is pushed into an empty array at array index 0.'
        ) : void
    {
        $a = [];
        array_push($a, 'zero');
        $this->assertSame('zero', $a[0], $description);
    }
}

And this is what it looks like in the docs with phpDocumentor:

phpDocumentor output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM