Bad practice: not using throwing tests


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


Can you guess what could be improved with this code?

As you’ve probably realized, this code is part of a unit test.

And inside this unit test, we need to call a function that can throw an error.

Currently, we handle it by calling the function inside a do block, and explicitly failing the test should an error be thrown.

But as it turns out, there’s actually no need to write all this extra code!

Instead we can simply mark the test itself as throwing:

Thanks to this change, we no longer need to use a do and a catch statement to call our throwing function, which makes our testing code both easier to read and quicker to write.

And if an error is thrown, then the testing framework will take care of catching it and automatically filling the test 👌

That’s all for this article, I hope this little trick will help you write tests better and faster!

Here’s the code if you want to experiment with it:

class Tests: XCTestCase {

    func test() throws {
        // ...

        try functionThatCanThrow()

        // ...
    }
}
Previous
Previous

Some APIs are more dangerous than they seem 🫢

Next
Next

Here are 3 Swift Macros you can start using today 🤌