參考博客:
iOS單元測(cè)試概念了解
iOS異步測(cè)試
Xcode:為你的項(xiàng)目集成單元測(cè)試(unit tests)時(shí)記得避開這些坑
1.創(chuàng)建測(cè)試工程
File-->New--->Target-->iOS Unit Testing Bundle
image.png
2.引用主工程
@testable import 主工程名
image.png
3.podfile中引入測(cè)試工程
target 'YStarTests' do
inherit! :search_paths
end
image.png
4.項(xiàng)目配置文件調(diào)整
-
Enable Testability
image.png -
info plist
image.png
5.單元測(cè)試編寫
image.png
- 邏輯測(cè)試
//邏輯測(cè)試舉例: 測(cè)試期望結(jié)果與實(shí)際結(jié)果是否相等
func testAdd(){
let expectValue = 20
let actualValue = 30
XCTAssertEqual(expectValue, actualValue)
}
- 功能測(cè)試
//功能測(cè)試:測(cè)試登錄功能(異步測(cè)試)
func testLogin() {
let expectOption = expectation(description: "登錄測(cè)試")
let param = LoginRequestModel()
param.phone = "18657195470"
param.pwd = "123456".md5()
AppAPIHelper.commen().login(model: param, complete: { (result) -> ()? in
if let object = result as? StarUserModel{
if let uid = object.userinfo?.id{
ShareModelHelper.instance().uid = Int(uid)
UserDefaults.standard.set(uid, forKey: AppConst.UserDefaultKey.uid.rawValue)
}
if let phone = object.userinfo?.phone{
ShareModelHelper.instance().phone = phone
UserDefaults.standard.set(phone, forKey: AppConst.UserDefaultKey.phone.rawValue)
}
ShareModelHelper.instance().token = object.token
UserDefaults.standard.set(object.token, forKey: AppConst.UserDefaultKey.token.rawValue)
expectOption.fulfill()
}
return nil
}, error: nil)
waitForExpectations(timeout: 15, handler: nil)
}
- 性能測(cè)試
//性能測(cè)試:測(cè)試登錄功能和Add方法性能表現(xiàn)
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
self.testLogin()
self.testAdd()
}
}
6.執(zhí)行單元測(cè)試
image.png
- 邏輯測(cè)試結(jié)果
邏輯測(cè)試.gif
- 功能測(cè)試結(jié)果
功能測(cè)試.gif
- 性能測(cè)試結(jié)果
性能測(cè)試.gif