A test case has four distinct phases:
- set up
- exercise
- verify
- tear down
Some of these phases can be empty. For example, most tear down happens automatically if you use ARC.
When you're starting, don't put anything into the setUp
or tearDown
methods. Just write a single unit test. Here's a worked example. (I'm going to change the names, because Objective-C idiom is not to use the word "get". So instead of getFlag
let's just call it flag
.) I'm going to call the class `Example, and I'll use ARC. And I use the abbreviation "sut" for "system under test".
- (void)testFlagGivenOneEntry
{
// set up
Example *sut = [[Example alloc] init];
[sut setTags:@{ @"key1" : @"value1" }];
// execute & verify
STAssertEqualObjects([sut flag], @"key1=\"value1\"", nil);
}
That's one test. Let's add another.
- (void)testFlagGivenTwoEntries
{
// set up
Example *sut = [[Example alloc] init];
[sut setTags:@{ @"key1" : @"value1",
@"key2" : @"value2" }];
// execute & verify
STAssertEqualObjects([sut flag], @"key1=\"value1\"&key2=\"value2\"", nil);
}
At this point, we have duplicate code: the creation of the sut. Now we can promote the variable up to an instance variable of the class. Then we create it in setUp
and destroy it in tearDown
:
@interface ExampleTest : SenTestCase
@end
@implementation ExampleTest
{
Example *sut;
}
- (void)setUp
{
[super setUp];
sut = [[Example alloc] init];
}
- (void)tearDown
{
sut = nil;
[super tearDown];
}
- (void)testFlagGivenOneEntry
{
[sut setTags:@{ @"key1" : @"value1" }];
STAssertEqualObjects([sut flag], @"key1=\"value1\"", nil);
}
- (void)testFlagGivenTwoEntries
{
[sut setTags:@{ @"key1" : @"value1",
@"key2" : @"value2" }];
STAssertEqualObjects([sut flag], @"key1=\"value1\"&key2=\"value2\"", nil);
}
@end
For a more involved example, see Objective-C TDD: How to Get Started.