XCtest.framework是苹果官方提供用于iOS/Mac单元测试的框架,最初版本是跟随iOS 10.0发布的,其使用简单直接,规则清晰,是iOS/Mac开发用于单元测试的主流工具,下面介绍一下其主要功能和使用指南。
创建测试用例
一般我们使用Xcode创建项目的时候,可以直接勾选“Include Tests”,这样系统会为我们同时创建XXXTests目录,目录下的文件XXXTests.m就是自动生成的单元测试代码模版。
我们先简单看下文件里面为我们提供的几个方法:
#import <XCTest/XCTest.h>
@interface XCTestDemoTests : XCTestCase
@end
@implementation XCTestDemoTests
- (void)setUp {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
- (void)testExample {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
@end
1. setUp方法会在每一个测试方法执行前运行,用于为测试方法执行准备环境和参数,应该把需要在测试方法开始前需要的代码都写在这个方法;
2. testExample方法是自动生成的一个示例,应该在这里调用需要的测试对象,并通过断言(Assertions)来检查结果是否符合预期;
断言(Assertions)
断言用来确认某些特定 条件是否为True,如果条件不满足,那么测试过程就会停止执行,断言的语法如下:
XCTAssert(condition, message)
第一个参数为需要判断满足的条件,第二个参数为条件不满足时候给出的提示信息(会在运行日志打印);
比如下面就是最简单的一个断言语句,这个断言结果为True所以是通过的。
XCTAssert(1 + 1 == 2, "1 + 1 does not equal 2")
XCTest.framework提供了现成的断言宏给我们直接调用:
1. 断言True/False
XCTAssertTrue(expression, ...)
XCTAssertFalse(expression, ...)
2. 断言Nil/Non-Nil
XCTAssertNil(expression, ...)
XCTAssertNotNil(expression, ...)
3. 断言Equal/Inequal
XCTAssertEqual(expression1, expression2, ...)
XCTAssertEqualObjects(expression1, expression2, ...)
XCTAssertNotEqual(expression1, expression2, ...)
XCTAssertNotEqualObjects(expression1, expression2, ...)
4. 断言Comparable Value
XCTAssertGreaterThan(expression1, expression2, ...)
XCTAssertGreaterThanOrEqual(expression1, expression2, ...)
XCTAssertLessThanOrEqual(expression1, expression2, ...)
XCTAssertLessThan(expression1, expression2, ...)
5. 断言Exception
XCTAssertThrows(expression, ...)
XCTAssertThrowsSpecific(expression, exception_class, ...)
XCTAssertThrowsSpecificNamed(expression, exception_class, exception_name, ...)
XCTAssertNoThrowSpecific(expression, exception_class, ...)
XCTAssertNoThrowSpecificNamed(expression, exception_class, exception_name, ...)
至此,关于XCTest.framework单元测试的相关内容介绍完毕,真正要写好单元测试重点在于理解要测试对象的所有逻辑分支,做到尽可能多的代码覆盖,灵活使用断言来判断各种分支的不同结果。