1. Create a projectwith ticking “include unit test” option inxcode.
* 生成的project会创建 2target, one for product app, one for unit test.
* For existingproject, to add unit test feature, just add a “unit testing bundle” type target
* By default, thereare 2 groups, one for product app, one for unit test. Unit test group里的.mfiles的property panel都是指向 unit test target。 而在product app group里的.mfiles都是指向product app target。不过2个group里的.hfiles都不指向任何target。有文章说对要被unit test的需要同时指向2个target,但我试了一下,好像不需要。
2. 先说requirement,要创建一个class叫Calculator, 会包含一个加法的method。
3. TDD,先写unittest:
* right click the unit testgroup, select “New File > Cocoa touch > objective c test case class”,click “next”
* set “Class” as “CalculatorTests”,click “Next”
* make sure unit test target is ticked, group is unit test, andfile path in unit test folder
* 代码如下
//CalculatorTests.h
#import<SenTestingKit/SenTestingKit.h>
@class Calculator;
@interface CalculatorTests : SenTestCase{
Calculator* calculator;
}
@end
//CalculatorTests.m
#import"CalculatorTests.h"
#import"Calculator.h"
@implementation CalculatorTests
-(void) setUp{
calculator = [[Calculator alloc] init];
}
-(void) tearDown{
calculator = nil;
}
@end
4. 上面代码编译错误,因为没有Calculatorclass存在。现在创建一个classnamed “Calculator”,记住target指向product app target。
5. 继续TDD, 添加下面测试加法method的代码 in CalculatorTest.m
-(void) testAdd {
STAssertEquals([calculator add: 2to:3], 5, @"2 + 3 result should be5");
}
6. 编译错误,因为Calculator里没有add:to: method. 添加下列代码
-(int) add: (int)a to: (int)b{
return a + b;
}
7. 这时运行”Test”,如果failed, error list就会出现在左边的panel