How to unit test throwing functions in Swift?

前端 未结 5 668
暗喜
暗喜 2021-02-01 12:56

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

5条回答
  •  没有蜡笔的小新
    2021-02-01 13:29

    At least of Xcode 7.3 (maybe earlier) you could use built-in XCTAssertThrowsError():

    XCTAssertThrowsError(try methodThatThrows())
    

    If nothing is thrown during test you'll see something like this:

    If you want to check if thrown error is of some concrete type, you could use errorHandler parameter of XCTAssertThrowsError():

    enum Error: ErrorType {
        case SomeExpectedError
        case SomeUnexpectedError
    }
    
    func functionThatThrows() throws {
        throw Error.SomeExpectedError
    }
    
    XCTAssertThrowsError(try functionThatThrows(), "some message") { (error) in
        XCTAssertEqual(error as? Error, Error.SomeExpectedError)
    }
    

提交回复
热议问题