Fixing your unit tests

You know that thing that happens when you love writing unit tests so much that you completely forget the argument order of all the assert(Equals|InstanceOf) functions.

Yeah it does happen, I’m sure it is not just me 😉

You write everything in as $this->assertEquals( function_call(), 'expected string' ); and then you get really confused when phpunit tells you it expects the wrong result from the function you haven’t implemented yet and received the expected result.

You do!

Good, I managed to write tests the wrong way round for two days before I realised and I wasn’t looking forward to going through and correcting them all, but then I remembered the power of sed and started cooking a recipe up.

It turned out pretty simple: sed -i "s/\(.*assert[^(]*\)( \([^,]*\), \([^)]*\) );/\1( \3, \2 );/" file_of_tests.php.

What it does:

  • Capture the start of the line up to the call to the assert function in ‘\1’
  • Capture the two function arguments in ‘\2’ and ‘\3’
  • Rewrite the matched line with the arguments switched

That was fun!