Backend Coder Logo

PHP Unit Testing Like Jasmine

Published: 18th February 2015

This is legacy material. Now I recommend PHP testing using my Easy Testing of PHP system.

Jasmine is a cool method of unit testing Javascript code that I came across when learning about Front-End coding. The standard way to do unit testing in PHP seems to be to use PHPUnit but I found it a bit hard to learn.

So, for fun I coded a Jasmine-like test runner in PHP.

Jasmine tested out Philip with a seductive stare across the computer room

Jasmine Concepts

I suggest that you read the Jasmine introductory notes that I linked to above since they explain the concepts very well in a short read.

The test code is self-documenting i.e. the names of the test functions read like English words that make sense of what is happening in the test code.

It runs through a series of tests that you group into blocks (suites of tests) that are encased in a global describe function. For example, a test suite could be called "Data Access".

Test specs define the various tests that you want to be run and are named with the name of the test suite.

PHP Code

I posted my code to Bit Bucket (see the link at the end of this post) so that you may download or clone it as a Git Repository. Also, you can see how I incorporated unit tests into my Otaku Pro project by browsing the source code.

My implementation uses global functions rather than Classes and encapsulated methods. This allows for simple, self-documenting test specs to be written in the style of the Jasmine Javascript testing framework.

The main difference in the test Spec format is:



The PHP implementation also entails using several global variables, so it's important that the names of the functions and global variables don't clash with those used in the code being tested.

If they do (unlikely), it should be easily spotted by exception errors being thrown, then the best course of action would be to rename the items in the code under test.

Test Output

The tests are ideally run as part of the build process. The output is in the form of green success messages, and the script terminates after any failed test with a red warning message.