Automated tests for the smallest parts of code.

The smallest testable part of an application is called a unit. Unit tests are written to test these units, usually automatically. There are many frameworks for various languages to make writing tests easier.

Unit tests not help you to check if your code still works after a change; they also force you write better code, because you have to separate each logical block to be able to write useful tests. A function fetching, changing and printing data is probably harder to test than three functions for each step.

PHP

In PHP, you can write simple tests with assert(), a function that takes a string and executes it as PHP code. Make sure you don’t push this code to your production server.

Example:

// Print test result
function test_output( $file, $line, $code )
{
    echo "Test failed at $file:$line: $code\n";
}

assert_options( ASSERT_ACTIVE,     1 );
assert_options( ASSERT_WARNING,    0 );
assert_options( ASSERT_QUIET_EVAL, 1 );

// Set up the result handler
assert_options( ASSERT_CALLBACK, 'test_output' );

function return_1() {
    return 1;
}

assert( '1 === return_1()' ); // pass, no message
assert( '2 === return_1()' ); // fail, show error message

Nowadays, unit tests in PHP are written on top of a framework. The most used is PHPUnit. WordPress core is using it too, see Automated Testing on make.wordpress.org and the link list at the end of this wiki.

JavaScript

Incomplete section. Please help us and edit this part.

See the link list for a start.

HTML & CSS

To test if HTML and CSS do what they should do, you have to render both together in a rendering engine (like a browser). So there aren’t actually testable units.

The WordPress Codex offers test data, and there is WP Test. Both are very useful, but not unit tests. Automated browser testing is done with tools like Selenium.

Links

The highest voted questions for unit-testing on Software Engineering and Stack Overflow are always worth a read.

PHP

JavaScript

history | excerpt history