With the addition of error handling to Swift 2, we got a way to deal with errors with the nice try/catch exception handling syntax from many languages,
but without the associated cost of stack unwinding.
As with anything new, some questions come to mind. How do we test methods that can throw errors? In Objective-C we had a few XCTest assert macros to help with this, like XCTAssertThrows. Swift 1 does not support exceptions, so these macros,
which get translated to Swift functions, are absent from the XCTest framework in Swift. I was expecting to find them in the Swift 2 version of the framework,
but they’re missing.
So the first thing that comes to mind is to just wrap the asserts into do/catch blocks.
And Xcode complains: “Call can throw, but it is executed in a non-throwing autoclosure.”
Assert macros use the @autoclosure attribute, so everything you pass to them becomes a closure. A non-throwing closure.
So you need to first try to get the result and pass just that.
This works. But, we hate repetition, don’t we?
Good. We can check if a method throws or not. But some methods return things and we would like to compare these things to other things.
Ok, that’s equality. But what about >, < and membership checks? Let’s add a validator closure then.