Monday, December 07, 2009

Easiest iPhone unit-testing ever using Google Toolbox for Mac

One of the reasons why I wasn't actually writing iPhone/Mac unit tests for a long time is that setting them up using SenTestingKit is a bit... tricky. Even when you know how to do it, it takes rather a lot of time.

Fortunately, there is Google Toolbox for Mac. It's a collection of different source code which Google uses in its own Mac/iPhone projects. And this toolbox has some nice stuff for unit-testing as well.

Here is a little cheat sheet which I use then I need to set up unit tests in my project:

1. Create "Tests" group in your project.
2. Of course, you don't need the whole toolbox. Therefore I have a minimalistic set of required source files. You can download it here. Then copy folder called as "UnitTesting" to (project)/Tests.
3. Create a new build target and say call it "Unit Tests". The target should have "Application" type.
4. Open the newly created target and add Run Script phase to the end
5. Set script contents to

"$SOURCE_ROOT/Classes/UnitTesting/RunIPhoneUnitTest.sh"

6. Ensure using finder, that the mentioned file above is actually present ($SOURCE_ROOT is your project's folder) and has executable bit set. Adjust this path in case of any different layout.
7. Add all .m source files from UnitTesting group to the target
8. Add all necessary code for your tests
9. Removed all source files from Tests group from you main target (since XCode automatically added them there)

That's it. Now you can write tests as follows:

MySuperTest.m:

#import "GTMSenTestCase.h"

@interface MySuperTest : GTMTestCase {
}
@end

@implementation MySuperTest

- (void)setUp
{
}

- (void)tearDown
{
}

- (void)test1
{
STAssertNotNil(obj, @"");
}

@end


Since GTM uses SenTestingKit you can use the same assertion macroses as with SenTest. Also please note, that you can have just an .m file. (it isn't related to GTM/SenTest, just a convenient practice since you rarely #import test files)

One of the biggest benefits of using GTM is that you have tests as application-type target. That means that you can debug tests just by running the appropriate target with enabled breakpoints. And of course, you can debug tests not only in the simulator, but on a real iPhone as well.

0 comments:

Post a Comment