Unit Testing Basic Html Output - assertTag

Published on:
Tags: PHP, Personal

About 18 months ago I started to dabble with unit testing within PHP, I first looked at simpletest before ultimately settling with PHPUnit. I was a little cautious at first, primarily concerned with the amount of time writing the tests were taking and maintenance of said tests, but soon realised their full potential.

It’s safe to say now I couldn’t really imagine developing anything of significant size without them, and I just simply havn’t yet come across any argument which can go anyway to persuading me otherwise. One exceptionally useful tool I make use of is code coverage analysis using xdebug with PHPUnit. This is an amazing tool which will analyze my tests telling me exactly what code (at class, function or line level) is covered by which tests, and how many times. More important than telling me which code IS covered it will tell me what code IS NOT covered. Cyclomatic complexity tells us that the number of unique linearly independent paths through a function relates directly to that functions complexity, to accurately test this function we need to cover all possible execution paths. Code coverage analysis flags this up for us in a clear, readable fashion – brilliant.

I would frequently notice when running these analysis that the same areas of my applications were always lacking in test case coverage – helpers. I often place code for repetitive rendering functions, possibly generating select lists, or different types of entity specific html widgets inside helpers, these functions were frequently poorly tested, similarly these functions often exhibited poor reliability, or were the first to suffer at the hand of any system regression.

That is until I came across this test assertion which allows you to test html output, for tags matching certain criteria, it’s a really lightweight option to allow for some pretty in-depth testing:

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
//Load dataset
$html = entity_helper::build_table();

$matcher = array(
  'tag' => 'table',
  'attributes' => array(
      'id' => 'entity-table'
  ),
  'children' => array(
      'count' => 6,
      'only' => array(
          'tag' => 'tr'
      )
  )
);

$this->assertTag($matcher, $html);

The above will ensure that a valid table is produced, with exactly 6 rows and an id of ‘entity-table’.  It’s easy to incorparate this type of testing as part of a larger assertion as well, for example you could make sure that a rendering helper generates a table with the correct amount of rows after a DB insert has been made, (i.e. purging any existing caches etc), and so on…

Check the available testable parameters for assertTag, you’ll be amazed at the flexibility it offers, and I guarantee that your code will benefit as a result of covering these things.

/Matt