XCTest是苹果官方的测试框架,是基于OCUnit的传统测试框架,测试编写起来非常简单。
参考文档:iOS Unit Testing and UI Testing Tutorial | Kodeco, the new raywenderlich.com
创建一个单元测试
- func testExample() throws {
- let personID:String = "0123456789"
- let count = personID.count
- XCTAssert(count <= 10, "ID length error.")
- // This is an example of a functional test case.
- // Use XCTAssert and related functions to verify your tests produce the correct results.
- // Any test you write for XCTest can be annotated as throws and async.
- // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error.
- // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards.
- }


常用的一些断言
XCTAssertEqualObjects:当两个对象不相等或者是其中一个对象为nil时,断言失败。
XCTAssertEquals:当参数1不等于参数2时断言失败,用于基本数据测试。
XCTAssertNil:当参数不是nil时,断言失败。
XCTAssertNotNil:当参数是nil时,断言失败。
XCTAssertTrue:当表达式为false时,断言失败。
XCTAssertFalse:当表达式为true时,断言失败。
XCTAssertThrows:如果表达式没有抛出异常,则断言失败。
XCTAssertNoThrow:如果表达式抛出异常,则断言失败
EmailUtil.swift
- import Foundation
-
- class EmailUtil {
- func validateEmail(email:String) -> Bool {
- //这里传入的参数,需要补充一下关于正则表达式的一些相关知识,学习链接放在文末。
- let pattern = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
-
- let matcher = RegexHelper(pattern: pattern)
-
- let result = matcher.match(input: email)
-
- if result {
- return true
- }else{
- return false
- }
- }
- }
RegexHelper.swift
- import Foundation
-
- struct RegexHelper {
- let regex : NSRegularExpression?
-
- init(pattern:String) {
- do {
- regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
- } catch {
- regex = nil
- }
- }
-
- func match(input:String) -> Bool {
- let matches = regex?.matches(in: input, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, input.lengthOfBytes(using: String.Encoding.utf8)))
-
- if (matches != nil) {
- return matches!.count > 0
- }else{
- return false
- }
- }
- }
创建测试案例 EmailTester

- import XCTest
-
-
-
- final class EmailTester: XCTestCase {
-
- func testEmail() throws {
- let emailUtil = EmailUtil()
- let result = emailUtil.validateEmail(email: "s1@163.")
- XCTAssert(result,"邮箱格式不正确")
- }
-
- }
会报错:Cannot find xxxx in scope ,改一下Target Membership

测试符合预期

修改邮箱

测试通过
- func testPerformanceExample() throws {
- measure {
- for _ in 0...600 {
- let image = UIImage(named: "wind")
- print(image?.size)
- }
- }
- }

iPhone开发Swift基础06 单元测试和界面测试_乐事派的博客-CSDN博客_swift 单元测试
官网