How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType is thrown?

推荐答案

EDIT: Updated the code for Swift 4.1 (still valid with Swift 5.2)

Here's the latest Swift version of Fyodor Volchyok's answer who used XCTAssertThrowsError:

    enum MyError: Error {
        case someExpectedError
        case someUnexpectedError
    }

    func functionThatThrows() throws {
        throw MyError.someExpectedError
    }

    func testFunctionThatThrows() {
        XCTAssertThrowsError(try functionThatThrows()) { error in
            XCTAssertEqual(error as! MyError, MyError.someExpectedError)
        }
    }

If your Error enum has associated values, you can either have your Error enum conform to Equatable, or use the if case statement:

    enum MyError: Error, Equatable {
        case someExpectedError
        case someUnexpectedError
        case associatedValueError(value: Int)
    }

    func functionThatThrows() throws {
        throw MyError.associatedValueError(value: 10)
    }

    // Equatable pattern: simplest solution if you have a simple associated value that can be tested inside 1 XCTAssertEqual
    func testFunctionThatThrows() {
        XCTAssertThrowsError(try functionThatThrows()) { error in
            XCTAssertEqual(error as! MyError, MyError.associatedValueError(value: 10))
        }
    }

    // if case pattern: useful if you have one or more associated values more or less complex (struct, classes...)
    func testFunctionThatThrows() {
        XCTAssertThrowsError(try functionThatThrows()) { error in
            guard case MyError.associatedValueError(let value) = error else {
                return XCTFail()
            }

            XCTAssertEqual(value, 10)
            // if you have several values or if they require more complex tests, you can do it here
        }
    }

Swift相关问答推荐

当我点击模拟器中的文本字段时,UIKit CLLocationButton崩溃

Swift数据关系

减小SF符号的边框宽度

在Swift中如何将NSUrl转换为本地路径URL

应该在ViewModel还是ViewController中使用"Task {}"?

使用View()和List()无法显示影子

为什么无法在 Swift 中使用AVFoundation扫描 QRCode

从一个范围减go 多个范围

是否可以使用 .task 修饰符更新基于两个值的视图

为什么 id 不能通过 struct 从 Objective-C 移植到 Swift?

Swift - 给定一个像 30 的 Int 如何将范围数乘以 7?

为什么 switch 在 optional 中不接受 case nil?

Apple 的自然语言 API 返回意外结果

是否可以在 Swift 中创建通用闭包?

在 iOS 中使用 Swift 保存 PDF 文件并显示它们

Alamofire:如何全局处理错误

如何使用 swift 在 tableview 中填充两个不同数组的两个部分?

Swift UITableView reloadData 在一个闭包中

判断用户是否登录到 iCloud?Swift /iOS

tableView 部分标题消失 SWIFT