The Digital Agency for International Development

Integration testing and closing PHP tags

By Martin Burchell on 05 February 2014

At Aptivate we recently started having "tech forum" meetings to share ideas between developers. Although we try to pair up on technical tasks where possible, we often have only one or two developers working on each project. So without these meetings there is a risk that different project teams might end up building multiple solutions to solve the same problem.

In these meetings, we've talked quite a bit about testing and how much integration testing is necessary, in comparison to unit testing.

When I was working on some PHP code to integrate with the new authentication system for Research4Life, all of my PHPUnit tests were passing but one of my HttpUnit integration tests was failing:


This was surprising because I hadn't touched any of the Journal export code. When I looked at the expected and actual output, the CSV export had gained a leading space right at the beginning of the file.

I'd seen this sort of thing before when white space appears outside PHP tags. Normally in a web page it doesn't really matter as the browser will ignore excess white space but for a CSV export this could affect the output of the file.

It wasn't obvious how this space had been introduced. I put some print statements in various places and narrowed it down to shortly before an object of class UserDetails was created.

PHP has a feature whereby you can define a custom class autoloader. This eliminates the need to have a long list of includes at the beginning of each script. Whenever an undefined class is encountered, the autoloader function is called, which includes the file. I changed my class autoloader to dump the name of each class.

The first line of the CSV output then looked like this: ...UserDetailsCountryCategoryPaidStatusCodeInstitution OfferTypeQuery...

So I found the extra space after the close PHP tag in the file that defines the Institution class. Removing it caused the test to pass again.

The reason that this file was now being included was because my UserDetails class now contained the line:

protected $institution_type = Institution::Unknown;

I think this bug would have been difficult to spot had the integration test not failed and I certainly wouldn't have thought to test CSV export as part of my manual testing of the authentication system.

I've since learned that omitting close PHP tags in pure PHP files is preferable for precisely this reason. I've configured Eclipse to stop closing them automatically by default.