dracoblue.net

Automated Tests for your @example Code Tags

When I am working on craur, I try to keep every method well documented.

I define well documented in such way, that I don't document things, which php already knows (e.g. parameter count, type hinting, etc) or which are obvious when looking at the signature (e.g. type for parameter called: title).

One thing I tend to document, are examples (with @example-tag) how the code is useful. Let's take this example for the createFromHtml method in craur:

<?php
    /**
     * Create a new `Craur` from a given HTML-string.
     *
     * @example
     *     $node = Craur::createFromHtml('<html><head><title>Hans</title></head><body>Paul</body></html>');
     *     assert($node->get('html.head.title') == 'Hans');
     *     assert($node->get('html.body') == 'Paul');
     *
     * @return Craur
     */
    static function createFromHtml($html_string, $encoding = 'utf-8')
?>

What most people miss, when they create such example code: it will become stale. And dead documentation will be ignored as soon as it becomes incorrect.

It would be super awesome, if one could execute the @example code, when the unit tests are executed.

Since phpunit and other unit test frameworks, do lack this functionality, I wrote a small script which generates one big unit test suite with multiple tests out of all source classes. The resulting file is commited as php_doc_snippet_test.

It contains the following lines:

<?php

/* Craur#createFromHtml */

$node = Craur::createFromHtml('<html><head><title>Hans</title></head><body>Paul</body></html>');
assert($node->get('html.head.title') == 'Hans');
assert($node->get('html.body') == 'Paul');

As you can see the function name + class name is included as doc comment. Executing the generator script multiple times will result in the same file. Thus it's easy to keep the resulting file in the version control, too.

So my proposal: If you want to keep your @example tags in (rdoc, javadoc, phpdoc, jsdoc ... etc) up to date and tested: unit test them!

In java, javascript, open source, php, ruby, unit tests by
@ 17 Dec 2013, Comments at Reddit & Hackernews

Give something back

Were my blog posts useful to you? If you want to give back, support one of these charities, too!

Report hate in social media Campact e.V. With our technology and your help, we protect the oceans from plastic waste. Gesellschaft fur Freiheitsrechte e. V. The civil eye in the mediterranean

Recent Dev-Articles

Read recently

Recent Files

About