Testing Throwing Methods In Swift Actors
A few guidelines for smooth testing of concurrent code.
In an ideal world, testing should be part of the development process of an app. The truth, however, is that testing is not always in the mix, and that’s mostly because it requires additional time; an asset that’s often missing from developers, especially when it’s necessary to meet deadlines. Or it’s not considered important enough because we all suffer from the illusion that we can predict all possible outcomes of our code.
Undeniably, testing should be a recursive task in our workflow, but leaving the general discussion aside, what I would like to focus on in this post today is something quite specific. In particular, my intension is to highlight how to test error throwing methods which belong to actors; the new type presented in WWDC 2021 that provides an isolated context and helps avoid data races when needed to support concurrency in our apps. Consider this post to be a short of a quick tip that will show you the way to avoid certain unnecessary issues if you have not written tests using actors and concurrency before.
Getting started with a usual type
To demonstrate the point of this article, let me start with a simple type that has nothing to do with concurrency and actors. That is a class that contains a stored property and a method to update the property’s value:
As you figure out from the above implementation, the input value in the
set(value:) method is assigned to the
userValue property if only it belongs to the closed range 1...99. In any other case, an error is thrown from the method -that's why it's marked with
throws - and the error varies depending on the value itself.
CustomErrors type appearing in the above code is this: