新建iOS项目时,如下图勾选【Include Tests】选项,新建项目中就会包含单元测试功能

若新建时未勾选,则可以先选中你的Target,File -> New -> Target 选择UI Testing Bundle或Unit Testing Bundle新建单元测试模块

先看UnitTestTests.swift文件
import XCTest
@testable import UnitTest
class UnitTestTests: 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.
// 给出的单元测试例子,可以将测试代码写在这里 也可以新建一个test方法
}
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.
}
}
}

比如新建了一个工具类,里面有个求两数相加之和的方法
import Foundation
class UnitTool {
static func add(num1: Int, num2: Int) -> Int {
return num1 + num2
}
}
如果在VC中使用:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let result = UnitTool.add(num1: 20, num2: 100)
print("result = \(result)"); // 打印result = 120
}
}
单元测试

点击方法左侧的菱形按钮,执行完毕后,如下图则代表测试通过

若如下图,红色菱形图标则代表测试不通过

当然,也可以新建个test方法来进行测试:

PS: 内置XCTAssert类型比较多,依据自身测试情况选用不同的断言
如果测试量比较多,写在一个测试文件中显得文件量太大,可以新建新的test case,新建时选择Unit Test Case Class,使用方法一样的


网友评论