Wednesday, 7 April 2010

CodeIgniter Unit Testing

CodeIgniter includes a unit test library as part of the framework. Documentation is included with the standard docs. If you follow the instructions, you can set it up and use it quite easily. However, the default output format leaves a little bit to be desired. Each test generates a separate table. This quickly becomes unwieldy and not very useful as the more tests added create longer and longer pages.



To solve the problem modified the template a little so once a table is produced with a row for each test. Here is my code.



   1:  <h2>Unit Test Page</h2>
2: <p>This is the test page for the application.</p>
3:<?php
4:$str = '
5: <tr>
6: {rows}
7: <td style="border:1pt solid black;">{result}</td>
8: {/rows}
9: </tr>';
10:
11:$this->unit->set_template($str);
12:
13:// Sample Test 1
14:$test = 1 + 1;
15:$expected_result = 2;
16:$test_name = 'Adds one plus one';
17:$this->unit->run($test, $expected_result, $test_name);
18:
19:
20:?>
21:<table cellpadding="4" cellspacing="1" style="border:1pt solid black; font-size:9pt; width:625px">
22: <tr><th width="35%">Test Name</th><th>In Type</th><th>Test Type</th><th width="15%">Result</th><th width="0%">Path</th><th>No</th></tr>
23:<?php
24:// Create Report
25:echo $this->unit->report();
26:?>
27:</table>
28:
29:</body>
30:</html>


My template is defined on lines 4-9. Basically, we only want to output a row for each test. So lines 20-27 defines the table that contains the rows. This produces much more compressed output.

No comments:

Post a Comment