[iOS] 養成TDD好習慣(1):create first project with unit test

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

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章