Swiftly Bite #1: Testing Swift Optionals

When testing optionals in swift there are a couple of ways to do so. One of those is by introducing conditionals to our code (if, guard….), but that’s something we want to avoid in our tests because adding new flows is not something we desire for our tests.

How do we avoid this? We can make our tests fail in a way that interrupts the tests but does not disrupt the execution of other tests while avoiding to add conditions to our code. This is where recoverable and non-recoverable errors come into play. For the purposes of this article we only care about recoverable errors.

Crash

One way to avoid introducing conditionals to our code is to just let the test crash. When a test crashes Xcode will recover and resume the execution of the pending tests. You can do this by force unwrapping an optional, and if the value is nil the test will crash. Testing will be resumed but Xcode will give the following error:

Personally, I would rather avoid having Xcode restart to resume testing, and that’s where the next option comes in:

Throw

The other way to have a test fail is to have it throw an error. But as we all know, optionals do not throw when unwrapping. But that can easily be solved by adding a new function to the Optional enum. We just need to add a function that throws an error when the unpacking of the wrapped value is nil. We could do it as follows:

And this is what happens when the test throws an error while unpacking:

The first thing you can read is the message that we wanted to print in case of the unwrapping error to get more help in the debugger. The second part is what the debugger prints for the failure of the tests. It is clearly a less dramatic message than the one for the crash.

Conclusion

So, which one should you choose? — It’s up to you really. My suggestion would be to chose throws over crash since it won’t require Xcode to recover that much. Also for me, every time a test crashed while running at Xcode instead of the terminal, Xcode wouldn’t continue carrying out the remaining tests files but it would then keep going when a test threw an error.


For more information about recoverable and non-recoverable errors go read this great article by John Sundell


Swiftly Bite is a series of small “straight to the point” articles. My hope is to continue making more of this in the future talking about different things that can be explained in a brief manner.


If you enjoyed this article consider giving it some claps. Also, if you feel like it, you can follow me on twitter at @MikePT28 or here in Medium.