Unit Testing in Elgg

Do NOT do this on production environments!!

Elgg 1.7 and above includes PHP SimpleTest framework. Here you will see how to unit test in Elgg.

First of all, log into your dev environment with admin access. Go to:
Admin > Site Administration and change "Turn off debug mode (recommended)" to "Display errors and warnings".
Then we create a new plugin. This example would have the following structure:

|- mod 
|     |- utest 
|     |     |- manifest.xml
|     |     |- start.php
|     |     |- tests 
|     |     |     |- utest.php

manifest.xml

<?xml version="1.0" encoding="UTF-8"?>
<plugin_manifest>
<field key="author" value="Nazim Rahman" />
<field key="version" value="1.0" />
<field key="description" value="unit testing example" />
<field key="website" value="" />
<field key="copyright" value="" />
<field key="licence" value="GNU Public License version 2" />
<field key="elgg_version" value="2011071212" />
</plugin_manifest>

start.php

function utest_init() {
    register_plugin_hook('unit_test', 'system', 'utest_unit_tests');
}
function utest_unit_tests($hook, $type, $value, $params) {
    global $CONFIG;
    $value[] = $CONFIG->path . 'mod/utest/tests/utest.php';
    return $value;
}
function utest_function1() {
    $var = 1;
    if ($var == 1) { return true; } else { return false; }
}
register_elgg_event_handler('init','system','utest_init');

tests/utest.php

class UtestUnitTest extends ElggCoreUnitTest {
    public function testFunction1() {
        $value = utest_function1();
        $this->assertTrue($value);
    }
}

To run this unit test, you need of course enable the plugin utest. Then go to:

Admin > System Diagnostics > Execute All

Note that start.php itself does not contain any debugging code or unit testing code. The unit testing code is in separate file inside tests directory. This directory is not pushed to production.

The beauty of this solution is that you can test all your plugins in dev with one click even years after writing them.