单元测试步骤
1.File -> New -> Target, 选择单元测试Target,创建成功
如果项目是老项目,那需要手动创建一下UnitTest Target,如果项目里已经有了就忽略。
2.创建一个swift工具的测试类CalculatorTests
然后就可以在里面写单元测试用例了。
单元测试常用知识点
环境变量的管理
setUp()测试开始前,初始化要使用的环境变量
tearDown()测试结束后,清理使用的环境变量
控制测试用例的执行顺序
1.可以通过test+101这种形式,顺序会根据test后面的数字,先小,后大的顺序进行执行
2.使用测试用例组的形式,执行顺序会按照组中的顺序,由上到下进行执行
静态变量allTests中放置排序后的测试用例
|
1
2
3
|
static var allTests = [ testCase(CalculatorTests.testAddition), testCase(CalculatorTests.testSubtraction)] |
测试异步方法
使用XCTestExpectation测试异步方法
|
1
2
3
|
let expectation = XCTestExpectation(description: "HTTP request")expectation.fulfill()wait(for: [expectation], timeout: 5.0) |
方法的性能测试
使用tmeasure(metrics: [XCTMetric], block: () -> Void)做性能测试
func measure(metrics: [XCTMetric], block: () -> Void)是 XCTest 中的一个方法,用于执行一段代码块并测量其执行时间。
参数 metrics 是一个 XCTMetric 类型的数组,用于指定要测量的指标。当前支持的指标包括:
wallClockTime:代码块执行的实际时间;
userTime:代码块执行期间 CPU 时间花费的量;
runTime:代码块执行期间系统运行时间的量。
执行 measure 方法会启动一个计时器,在代码块执行完成后停止计时器并记录测量的指标值。可以在测试报告中看到测量结果。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
import XCTest@testable import ARDemo//创建CalculatorTests类,继承自XCTestCaseclass CalculatorTests: XCTestCase { var calculator: Calculator! //测试开始前,初始化要使用的环境变量 override func setUp() { super.setUp() calculator = Calculator() } //测试结束后,清理使用的环境变量 override func tearDown() { super.tearDown() calculator = nil } //要控制测试用例的执行顺序 //1.可以通过test+101这种形式,顺序会根据test后面的数字,先小,后大的顺序进行执行 func test101Addition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition of 2 and 3 should be 5") } func test102Addition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition of 2 and 3 should be 5") } func test103Addition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition of 2 and 3 should be 5") } //2.使用测试用例组的形式,执行顺序会按照组中的顺序,由上到下进行执行 func testAddition() { let result = calculator.add(2, 3) XCTAssertEqual(result, 5, "Addition result is incorrect") } func testSubtraction() { let result = calculator.subtract(5, 2) XCTAssertEqual(result, 3, "Subtraction result is incorrect") } //静态变量allTests中放置排序后的测试用例 static var allTests = [ testCase(CalculatorTests.testAddition), testCase(CalculatorTests.testSubtraction) ] //测试异步方法 func testAsyncHTTPRequest() { let expectation = XCTestExpectation(description: "HTTP request") // 调用异步HTTP请求方法 asyncHTTPRequest { response in // 处理回调结果 XCTAssertTrue(response.success) expectation.fulfill() } // 等待异步操作完成 wait(for: [expectation], timeout: 5.0) } //测试功能的执行性能 func testPerformance() { measure([.wallClockTime, .userTime]) { // 执行需要测试性能的代码块 } }}class Calculator { func add(_ a: Int, _ b: Int) -> Int { return a + b } func subtract(_ a: Int, _ b: Int) -> Int { return a - b }} |