Handling all the error scenarios of our functionality is very important. Swift provides a nice way to handle Errors. The happy path is, of course, the one that takes most of the focus and is usually the first one that is being tested. But that should not leave the alternative or error paths untested.
Errors in Swift are values of types that conform to the Error protocol. Normally we group related errors in enumerations.
Writing tests to verify that a function is throwing an Error is easy in Swift.
Let’s imagine that we have the FizzBuzz Kata but instead of return “Fizz”, “Buzz” or “FizzBuzz” we have to throw an Error. Our code will look like:
And we can use XCTAssertThrowsError to catch the Error and then use the XCTAssertEquals to check if it is the expected Error.
This logic of XCTAssertThrows and XCTAssertEqual can be useful in many tests, so instead of repeat the code we can use an extension with this logic (https://www.swiftbysundell.com/posts/testing-error-code-paths-in-swift)
And the tests can look like :
Github code:
https://github.com/Fragki/how-to-unit-test-serries
Resources:
https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html
https://www.swiftbysundell.com/posts/testing-error-code-paths-in-swift