Quick Tips: Testing Fatal Error

Have you ever needed to test something that throws a fatalError?

Here is a quick tip to help you do that.

The Problem

Let's suppose you want to test the code above. The way it is implemented, you would be unable to check if fatalError was called, since it would cause a crash.

Well there is a very simple hack to change this.

The Solution

You just need to copy the fatalError method and pass it as a parameter to your function, like you would do with any other closure.

The Test

By replacing the failureHandler closure with you own, using a minor delay and expectations, it is now possible to check if it was called and test your logic.


This little hack enables you to test functions like assertFailure, assert and fatalError, or actually almost any function that return Never and a side effect.
That's it, good testing for everyone! =)

iOS Engineer, AI enthusiast, Crossfit/Gymnastics. Currently working as iOS Lead @adidas