How to unit test throwing functions in Swift?

前端 未结 5 582
暗喜
暗喜 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:28

    You can use this function:

    func XCTAssertThrowsError(
      _ expression: @autoclosure () throws -> T,
      error: E,
      in file: StaticString = #file,
      line: UInt = #line
      ) {
      var thrownError: Error?
      XCTAssertThrowsError(
        try expression(),
        file: file,
        line: line) {
          thrownError = $0
      }
    
      XCTAssertTrue(
        thrownError is E,
        "Unexpected error type: \(type(of: thrownError))",
        file: file,
        line: line
      )
    
      XCTAssertEqual(
        thrownError as? E,
        error,
        file: file,
        line: line
      )
    }
    

    Example:

    XCTAssertThrowsError(try funcThatThrowsSpecificError(), error: SpecificErrorEnum.someError)
    

提交回复
热议问题