Swift下的单元测试 - ShenYj/ShenYj.github.io GitHub Wiki
主要是由于苹果官方框架的测试方法及断言不明确,可读性不好,难以分辨,交接项目需要花费的时间很多,所以建议采用三方测试框架
方案一: Quick + Nimble
方案二: Sleipnir
已经停更
用到的类库有:
-
Quick
是一个建立在XCTest
上,为Swift
和Objective-C
设计的测试框架. 对测试使用Swift
编写的App
非常友好,对Swift
使用者来说,Quick
是最佳选择。它通过
DSL
去编写非常类似于RSpec
的测试用例。默认状态下
Swift
单元测试类文件如下:import XCTest @testable import DemoApp class LoginPresenterTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
使用了
Quick
后:import Quick import Nimble @testable import DemoApp class LoginPresenterSpec: QuickSpec { override func spec() { describe("描述类和方法") { beforeEach { } context("指定条件或状态", closure: { beforeEach { } afterEach { } it("最小测试单元", closure: { }) }) } } }
-
对比
区别点 XCTest Quick 继承关系 继承自 XCTestCase
继承自 QuickSpec
文件命名规则 类名+ Tests
后缀类名+ Spec
测试方法规则 test
前缀+被测方法名+装态-
- 最直观的好处就是通过
Quick
, 就不用再依据被测方法及不同的装态而定义出长长的测试方法名称了 - 对比
OC
更为明显, 除了方法命名外, 一般通过注释对测试用例场景补充描述, 而使用了Quick
,相当于将注释+用例场景结合书写 - 这种书写方式也更加适合前端的人, 书写感受等同于
Jest
, 像我这样之前写OC
原生开发, 中途写了一阵子RN
的人来说, 这种测试代码风格无缝切换
-
关于
Quick
关键字说明:标签 说明 describe 用于描述类和方法 beforeSuite 相当于全局setUp afterSuite 相当于全局tearDown beforeEach 相当于setUp afterEach 相当于tearDown context 用于指定条件或状态 it 最小测试单元描述 在describe、context、it前加 x
表示可以屏蔽此方法的测试 在describe、context、it前加 f
表示可以只测试这些带f的测试
-
屏蔽
测试用例在方法名前加
x
,可以屏蔽此方法的测试, 如:xdescribe("its click") { // ...none of the code in this closure will be run. } xcontext("when the dolphin is not near anything interesting") { // ...none of the code in this closure will be run. } xit("is only emitted once") { // ...none of the code in this closure will be run. }
-
屏蔽
集中测试在方法名前加
f
,可以只测试这些加f
的测试, 如:fit("is loud") { // ...only this focused example will be run. } it("has a high frequency") { // ...this example is not focused, and will not be run. } fcontext("when the dolphin is near something interesting") { // ...examples in this group are also focused, so they'll be run. }
-
Nimble
就像是Quick
的搭档,它提供了匹配器作为断言,用于编写匹配模式。
TBD...
一些提高编写代码的技巧