Printed on: December 4, 2024
Swift’s new trendy testing framework is totally pushed by asynchronous code. Which means that all of our check capabilities are async and that we have now to be sure that we carry out all of our assertions “synchronously”.
This additionally signifies that completion handler-based code is just not as easy to check as code that leverages structured concurrency.
On this put up, we’ll discover two approaches that may be helpful if you’re testing code that makes use of callbacks or completion handlers in Swift Testing.
First, we’ll take a look at the built-in affirmation
methodology from the Swift Testing framework and why it may not be what you want. After that, we’ll take a look at leveraging continuations in your unit exams to check completion handler based mostly code.
Testing async code with Swift Testing’s confirmations
I’ll begin this part by stating that the primary cause that I’m masking affirmation
is that it’s current within the framework, and Apple suggests it as an choice for testing async code. As you’ll study on this part, affirmation
is an API that’s largely helpful in particular situations that, in my expertise, don’t occur all that always.
With that stated, let’s see what affirmation
can do for us.
Generally you may write code that runs asynchronously and produces occasions over time.
For instance, you may need a little bit of code that performs work in numerous steps, and through that work, sure progress occasions must be despatched down an AsyncStream
.
As standard with unit testing, we’re not going to actually care concerning the precise particulars of our occasion supply mechanism.
In truth, I will present you ways that is performed with a closure as an alternative of an async for loop. In the long run, the main points right here don’t matter. The principle factor that we’re considering proper now could be that we have now a course of that runs and this course of has some mechanism to tell us of occasions whereas this course of is going on.
Listed here are a number of the guidelines that we need to check:
- Our object has an
async
methodology referred to ascreateFile
that kicks of a course of that entails a number of steps. As soon as this methodology completes, the method is completed too. - The item additionally has a property
onStepCompleted
that we will assign a closure to. This closure known as for each accomplished step of our course of.
The onStepCompleted
closure will obtain one argument; the finished step. This will probably be a worth of sort FileCreationStep
:
enum FileCreationStep {
case fileRegistered, uploadStarted, uploadCompleted
}
With out affirmation
, we will write our unit check for this as follows:
@Check("File creation ought to undergo all three steps earlier than finishing")
func fileCreation() async throws {
var completedSteps: [FileCreationStep] = []
let supervisor = RemoteFileManager(onStepCompleted: { step in
completedSteps.append(step)
})
strive await supervisor.createFile()
#count on(completedSteps == [.fileRegistered, .uploadStarted, .uploadCompleted])
}
We will additionally refactor this code and leverage Apple’s affirmation
method to make our check look as follows:
@Check("File creation ought to undergo all three steps earlier than finishing")
func fileCreation() async throws {
strive await affirmation(expectedCount: 3) { verify in
var expectedSteps: [FileCreationStep] = [.fileRegistered, .uploadStarted, .uploadCompleted]
let supervisor = RemoteFileManager(onStepCompleted: { step in
#count on(expectedSteps.removeFirst() == step)
verify()
})
strive await supervisor.createFile()
}
}
As I’ve stated within the introduction of this part; affirmation
‘s advantages aren’t clear to me. However let’s go over what this code does…
We name affirmation
and we offer an anticipated variety of occasions we wish a affirmation occasion to happen.
Observe that we name the affirmation
with strive await
.
Which means that our check is not going to full till the decision to our affirmation
completes.
We additionally go a closure to our affirmation
name. This closure receives a verify
object that we will name for each occasion that we obtain to sign an occasion has occurred.
On the finish of my affirmation closure I name strive await supervisor.createFile()
. This kicks off the method and in my onStepCompleted
closure I confirm that I’ve obtained the suitable step, and I sign that we’ve obtained our occasion by calling verify
.
Right here’s what’s fascinating about affirmation
although…
We should name the verify
object the anticipated variety of occasions earlier than our closure returns.
Which means that it’s not usable if you need to check code that’s absolutely completion handler based mostly since that may imply that the closure returns earlier than you’ll be able to name your affirmation
the anticipated variety of occasions.
Right here’s an instance:
@Check("File creation ought to undergo all three steps earlier than finishing")
func fileCreationCompletionHandler() async throws {
await affirmation { verify in
let expectedSteps: [FileCreationStep] = [.fileRegistered, .uploadStarted, .uploadCompleted]
var receivedSteps: [FileCreationStep] = []
let supervisor = RemoteFileManager(onStepCompleted: { step in
receivedSteps.append(step)
})
supervisor.createFile {
#count on(receivedSteps == expectedSteps)
verify()
}
}
}
Discover that I’m nonetheless awaiting my name to affirmation
. As a substitute of 3
I go no anticipated depend. Which means that our verify
ought to solely be referred to as as soon as.
Inside the closure, I’m working my completion handler based mostly name to createFile
and in its completion handler I verify that we’ve obtained all anticipated steps after which I name verify()
to sign that we’ve carried out our completion handler based mostly work.
Sadly, this check is not going to work.
The closure returns earlier than the completion handler that I’ve handed to createFile
has been referred to as. Which means that we don’t name verify
earlier than the affirmation’s closure returns, and that leads to a failing check.
So, let’s check out how we will change this in order that we will check our completion handler based mostly code in Swift Testing.
Testing completion handlers with continuations
Swift concurrency comes with a function referred to as continuations. In case you are not accustomed to them, I might extremely suggest that you simply learn my put up the place I am going into how you should utilize continuations. For the rest of this part, I will assume that you already know continuations fundamentals. I’ll simply take a look at how they work within the context of Swift testing.
The issue that we’re attempting to resolve is actually that we don’t want our check perform to return till our completion handler based mostly code has absolutely executed. Within the earlier part, we noticed how utilizing a affirmation
does not fairly work as a result of the affirmation closure returns earlier than the file managers create file finishes its work and calls its completion handler.
As a substitute of a affirmation
, we will have our check await a continuation
. Inside the continuation
, we will name our completion handler based mostly APIs after which resume the continuation when our callback known as and we all know that we have performed all of the work that we have to do. Let’s have a look at what that appears like in a check.
@Check("File creation ought to undergo all three steps earlier than finishing")
func fileCreationCompletionHandler() async throws {
await withCheckedContinuation { continuation in
let expectedSteps: [FileCreationStep] = [.fileRegistered, .uploadStarted, .uploadCompleted]
var receivedSteps: [FileCreationStep] = []
let supervisor = RemoteFileManager(onStepCompleted: { step in
receivedSteps.append(step)
})
supervisor.createFile {
#count on(receivedSteps == expectedSteps)
continuation.resume(returning: ())
}
}
}
This check seems similar to the check that you simply noticed earlier than, however as an alternative of ready for a affirmation, we’re now calling the withCheckedContinuation
perform. Inside the closure that we handed to that perform, we carry out the very same work that we carried out earlier than.
Nevertheless, within the createFile
perform’s completion handler, we resume the continuation solely after we have made positive that the obtained steps from our onStepCompleted
closure match with the steps to be anticipated.
So we’re nonetheless testing the very same factor, however this time our check is definitely going to work. That is as a result of the continuation will droop our check till we resume the continuation.
While you’re testing completion handler based mostly code, I normally discover that I’ll attain for this as an alternative of reaching for a affirmation
as a result of a affirmation
doesn’t work for code that doesn’t have one thing to await
.
In Abstract
On this put up, we explored the variations between continuations
and confirmations
for testing asynchronous code.
You have realized that Apple’s advisable method for testing closure based mostly asynchronous code is with confirmations
. Nevertheless, on this put up, we noticed that we have now to name our verify
object earlier than the affirmation closure returns, in order that signifies that we have to have one thing asynchronous that we await
for, which is not all the time the case.
Then I confirmed you that if you wish to check a extra conventional completion handler based mostly API, which might be what you are going to be doing, you need to be utilizing continuations
as a result of these permit our exams to droop.
We will resume a continuation
when the asynchronous work that we have been ready for is accomplished and we’ve asserted the outcomes of our asynchronous work are what we’d like them to be utilizing the #count on
or #require
macros.