[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

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值