Tuesday, September 29, 2009

Unit testing on the iPhone SDK

I have been busy preparing lectures (still am) but I'm still alive :)


I realised that I was adding code to the iPhone project more like in a prototyping stage. I wasn't doing any tests but I still tried to organize the classes as best as I could. Now I'm starting to loose confidence when I'm going to add some features. Not a good feeling. I want to switch to TDD (Test Driven Development), where you first write a failing test, and then write the production code. The excellent side effect of this is that the design of the classes are automatically decoupled. However I need to first convert my project to be covered by tests. Found an interesting book called "Working Effectively with Legacy Code" where it gives a lot of tips on how to breakdown classes, etc. I'm still reading it in my free time, but I will soon be putting the tips to work.

Setting up test harness
I searched for setting up a test harness in XCode. Version 3 supports unit tests using the SenTesting classes. I found a presentation and an Apple support page to set up a test harness. It also describes for setting up functional testing, however I will be only using unit (logic) tests for now.

Some tips to finalize the setup

Remember to drag any .m files into the Compile Sources in the logic tests target and also any libraries.
Also edit the Active target LogicTests and under Build tab, in Gcc 4.2 - Language section, turn on Precompile Prefix Header and also set the Prefix Header to _Prefix.pch
It is very important to this as otherwise it will give you loads of errors like could not find CGPoint class, etc

NSLog...where are they output?
What about logging when running the tests? Since to execute the unit tests you just need to build the application, there is not console out from XCode, however you can view the output of NSLog statements in the Console application. Launch Console from Spotlight.

Code Coverage
I also wanted to have code coverage, to know how much of the code is being tests by the tests. I found an excellent tutorial on setting up code coverage. It uses CoverStory - a tool for viewing the results of code coverage.

Now I need to rewire my brain to think in tests...