After struggling with an illogical UI I finally figured out how to add unit tests to an existing project in XCode 4.2.
Open your project.
Goto File -> New -> New Target
Select iOS Cocoa Touch bundle.
Give it a name like ‘LogicTests’
Then click on your blue app area in your navigation.
Then click ‘Build Phases’ and expand the Target Dependency area. See how it’s blank?
That’s a problem. We need to add your application here so your unit test target is linked to your app.
So go ahead and click the ‘+’ sign and add your application.
Now you should be able to run your unit tests (by holding down the build icon until it turns to a test icon).
When you do you’ll see a configure app for testing window pop-up.
Just click ‘Edit Scheme…’ hit the plus sign (making sure the Test/Debug panel is highlighted) and add your unit test scheme as shown below.
Now you can hit that test button and all your unit tests should run.
There’s a gotcha
There’s one more gotcha you need to be aware of. As of XCode 4.2 when you add a new test class
You will get a screen that looks like this:
The defaults here are wrong. The MyApp shouldn’t be selected. We want the unit test target ‘Logic Tests’ to be checked.
If you accept these, when you go to run your tests you’ll get an error like:
<SenTestingKit/SenTestingKit.h> file not found.
This occured because the wizard default added your new test class to your main project and not your test target.
You can manually fix this by going into the build phase of your project and adding your test file to your test target and removing it from your main application target under the ‘Compile Sources’ tab.
Or you can just create the class from scratch and select your test project and not the application one.
Hope this helps. Happy testing!
Feb 27, 2012 @ 23:13:29
Note: I just tried this on XCode 4.3 and it looks like they fixed the default.
The test class you get is different.
But at least your test should be added to the right target.
Feb 27, 2012 @ 23:59:55
Thanks. I tried to do something similar when adding tests to an existing target. If you want Application rather than Logic tests, I had a few extra steps to set up… although I still wonder why Apple bothers to refer to these different types of tests.
http://sgleadow.github.com/blog/2011/10/30/adding-unit-tests-to-an-existing-ios-project/
http://twobitlabs.com/2011/06/adding-ocunit-to-an-existing-ios-project-with-xcode-4/
Feb 28, 2012 @ 18:14:24
Those are great Stewart. Thanks.
Looking forward to writing some application tests.
Those links will definitely help.
Oct 09, 2012 @ 12:21:08
excellent tutorial, though I’m a bit stuck at adding logic tests to my app (app tests work fine!) I’ve done all the things but tests do not run. Can you please try to answer my question on stackoverflow? Here’s the link http://stackoverflow.com/questions/12781589/adding-logic-tests-to-the-project-in-xcode-4-5