How to test wether a function in Swift 2.0 throws or not? How to assert that the correct ErrorType
is thrown?
Given the following functions and declarations:
enum SomeError: ErrorType {
case FifthError
case FirstError
}
func throwingFunction(x: Int) throws {
switch x {
case 1:
throw SomeError.FirstError
case 5:
throw SomeError.FifthError
default:
return
}
}
This function will throw a FifthError
if 5 is given to the function and FirstError
if 1 is given.
To test, that a function successfully runs the unit test could look as follows:
func testNotError() {
guard let _ = try? throwingFunction(2) else {
XCTFail("Error thrown")
return
}
}
The let _
may also be replaced by any other name, so you can further test the output.
To assert that a function throws, no matter what ErrorType
the unit test could look like this:
func testError() {
if let _ = try? throwingFunction(5) {
XCTFail("No error thrown")
return
}
}
If you want to test for a specific ErrorType
it's done with a do-catch
-statement. This is not the best way compared to other languages.
You have to make sure that you...
return
in the catch
for the correct ErrorType
XCTFail()
and return
for all other catch
XCTFail()
if no catch
is executedGiven this requirements a test case could look like this:
func testFifthError() {
do {
try throwingFunction(5)
} catch SomeError.FifthError {
return
} catch {
XCTFail("Wrong error thrown")
return
}
XCTFail("No error thrown")
}