Unit Tests with iOS and XCode4
Since nearly 1 year I am developing iPhone applications but until last week I never found time to write and run unit tests even though in XCode4 it asks you if one want to include unit tests into the App. But it was just a question of time until I have to start using it. So one of my Apps started to fail over and over again because the web service calls either changed or just did not work. This became very tedious because I had to go through a ton of log files to figure out what didn’t work. Thus it finally was time to invest the time to create the unit tests so that the API is tested with little effort and I have a quick result on what is broken.
As usual the road to bliss was plastered with stepping stones, pitfalls and some frustrations which made it more difficult that expected but it did not prevent me from reaching my goal. These are the steps I had to take to make it work:
- If not already done create a new file of type Object-C test case class
- To begin with write a simple no-op test method with a NSLog statement so that you know when it is executed
- Go to the Project Configuration, select the test target, select all on the top and look for the group Unit Testing. There you set Test after Build to Yes.
- On the top left select the XXXTest schema and click on run
- To check the log please go to the log navigator (command-7) and select the top most log entry
- Inside there you look for Run custom shell script, select that row and hit the staple icon on the right. This will open the log view below.
- Now you can see if the test was executed
So far we made the test execute but if we try to test any of our classes we probably fail with a linker error. This is because XCode4 per se does not add any regular classes into the test environment except we already did that when adding the class to XCode. That said we can do that easily:
- Go back to the project configuration
- Select the test target
- Click on Build Phases
- Select Compile Sources
- Now we can add any implementation class file that we need to run the test. Please don’t add headers to this list (.h files)
- We might to repeat this a few times until we get all the necessary classes in
Now we can start writing tests that uses the classes we have. For now I only tested non-UI classes and I had to go ahead and use a switch in some of the classes to not use UI components otherwise the test would fail. I am not sure if there is a way to test UI components in the unit tests. On the bright side this forces developers to separate UI and service code more thoroughly which is not a bad thing either.
Cheers – Andy
Comments are closed.