与上一种添加方式不同的是,在Scheme列表中会添加一个LogicTest,这也是我们需要注意的,这也是应用单元测试和逻辑单元测试的另一个 不同之处。运行它需要选择Scheme中LogicTest的iPhone 6.0 Simulator(或iPad 6.0 Simulator)运行,但是不能选择iOS Device,逻辑单元测试只能在模拟器中运行。然后再选择菜单Product→Test、工具栏中Test按钮(下拉Run按钮选择)和快捷键 command+U等几种方式运行。
无论那种方式添加,默认生成的测试类基本都是一样的,下面代码是默认生成的LogicTest测试类中的LogicTest.h和LogicTest.m文件。
// // LogicTest.h // LogicTest // #import <SenTestingKit/SenTestingKit.h> @interface LogicTest : SenTestCase @end // // LogicTest.m // LogicTest // #import “LogicTest.h” @implementation LogicTest - (void)setUp { [super setUp]; // Set-up code here. } - (void)tearDown { // Tear-down code here. [super tearDown]; } - (void)testExample { STFail(@”Unit tests are not implemented yet in LogicTest”); } @end |
作为OCUnit测试类需要引入<SenTestingKit/SenTestingKit.h>头文件,并继承 SenTestCase父类。testExample方法是一般的测试方法,方法名必须test开头,测试方法的个数没有限制,方法中STFail是 OCUnit框架定义的一个宏,是无条件断言失败,实际使用时候要修改这个方法中的代码。
在m文件中需要重新方法setUp和tearDown,我们自己编写的测试类一样,setUp方法是初始化方法,tearDown方法是释放资源的 方法,setUp和tearDown方法在每次调用测试方法之前和之后调用,因此在测试类运行的生命周期中这两个方法可能多次运行,它们的时序图