Actions

Unit Testing -- UI Example

From Joomla! Documentation

Revision as of 17:29, 24 June 2008 by Instance (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Testing User Interface Code

This expands on the basics given in the Simple Example. In this example, we want to test a class that outputs code to the browser.

PHPUnit has an extension to support this, but it's pretty limited. You can extend your test class from PHPUnit_Extensions_OutputTestCase, and then use assertions like $this->expectOutputString('foo') and $this -> expectOutputRegex($regex) to verify that the output contains the string you're looking for. That technique works for simple cases, but if the method you want to test takes complex parameters or generates a lot of code, it's just not enough.

Capturing Output

This snippet from a test demonstrates the method for capturing data.

ob_start();
HTML_modules::add($modules, $this -> client);
$result = ob_get_flush();

The $result now variable has everything that would normally go to the browser.

Verifying the Output

Now that we have the output, how do we make sure it is "correct"?

In this example, there are two defining characteristics to the output: each module should be rendered as a radio button and a link. Let's look for the radio buttons first.

                // Get contents of all radio buttons
                preg_match_all('|<input .*type="radio".*>|U', $result, $matches);
                // Filter for name=module
                foreach ($matches[0] as $index => $subs) {
                        if (strpos($subs, 'name="module"') === false) {
                                unset($matches[0][$index]);
                        }
                }
                $this -> assertEquals(count($modules), count($matches[0]), 'Number of radio buttons.');