I’ve been doing a lot of development using the CodeIgniter framework for the last few months. I’ve been looking to get into TDD, but upon inspection, I found the CodeIgniter unit tests to be a little lacking. One of the things I feel is a must for decent testing of a web app is a database mock. 90% of what I’m doing is moving data back and forth to the database, it’s also the most error prone code. I put my test class in a controller so that it was completely self contained, you could move it to a model if that would fit better. It should be easily extendible. It has a number of type check unit tests built in. It also has a setup_mock_db function that expects to find a ‘test’ database. WARNING: this function completely drops all tables it find in the test database, so use it carefully. The idea here is that you can make schema changes to your development database and they will be automatically reflected to your unit testing. Also, I know, if I’m talking to a database it’s not technically a unit test – but if I’m not talking to a database it’s not technically helpful, at least I’m not talking to the main database, but a dedicated testing database.
When the unit test are called, most take two argument, some take three. The first argument is the result of a function. This result is going to be type checked. In the cases that take three arguments, the second argument is used for comparison (is_equal, is_not_equal). The third argument is the name of the test, this gets printed in the results report so you can identify what you were testing. I normally use a chunk of code here. Here’s what some of my unit tests look like
$this->is_false($this->user_model->is_valid_email("not an email"), 'is_valid_email("not an email")'); $this->is_null($this->user_model->log_out(), 'log_out()');
Here’s the actual controller class, I’ve removed my tests. I generally break up the tests into chunks so that I can test portions of my site. I then use the index method to call all of the chunks so I can test the whole site at once. I print a lot of HTML raw because I didn’t want to have to build views to go with this. Just drop in the controller and the unit testing is all set to go.