This article should be considered an example of creating a result printer for PHPUnit tests. Nevertheless, the use case described here is totally invalid in my opinion.

PHPUnit 3.6 allows us to create our own so-called ResultPrinters. Using such a printer is quite necessary in the case of running your unit tests from within the browser (see my previous post), since we don't print to a console, but to a screen. You can make this all as nice as you like, but here is the basic version of it.

Create the HtmlResultPrinter

First create the file containing your (for example) HtmlResultPrinter, for example in /src/Acme/DemoBundle/PHPUnit/HtmlResultPrinter.

Because normally browsers wait until the complete response was received from the server, before they start to render anything, we start output buffering. The we set autoFlush to true, which means that as soon as something is written using the ResultPrinter's write() method, the output should be flushed to the browser.

As you can see, we also override the $colors parameter of the call to parent::__construct(), so no colors will be rendered (since this will give a strange result in HTML).

Replace write()

While trying to accomplish this, I found out that the write() method needed to be replaced by a slightly different one:

First of all: I let this method replace any new line characters by HTML new lines (). Second, the output should reach some critical mass, before it gets processed by a browser; therefore I add padding to every outputted string. Without it, the browser still waits with rendering the content until everything is received.

Finally; I also removed the call to htmlspecialchars() from the original write() method. This will prevent double escaping of HTML characters (like "<" or ">"). Note that if you override any other methods of the ResultPrinter, it is now your own responsibility to take care of output escaping.

Replace incrementalFlush()

Then, upon autoFlush, the method incrementalFlush() gets called. But nothing gets flushed really, since we are using output buffering. So right before flush() gets called (and the output is sent to the browser), the output buffer needs to be flushed also. The ResultPrinter's incrementalFlush() method should thus look like this:

First, we need to make sure the HtmlResultPrinter class is loaded (otherwise PHPUnit will try to do so and fail). Then, we have to add the --printer command line option to tell PHPUnit which ResultPrinter it should use.

Now we can now decorate the standard TextUI_ResultPrinter methods with our own methods for enhancing the rendered results. For example, wrap each defect in a <div> with a class "defect":