Testing completion handler primarily based code in Swift Testing – Donny Wals

Testing completion handler primarily based code in Swift Testing – Donny Wals


Revealed on: December 4, 2024

Swift’s new fashionable testing framework is solely pushed by asynchronous code. Which means that all of our check features are async and that we have now to ensure that we carry out all of our assertions “synchronously”.

This additionally signifies that completion handler-based code shouldn’t be as easy to check as code that leverages structured concurrency.

On this put up, we’ll discover two approaches that may be helpful whenever you’re testing code that makes use of callbacks or completion handlers in Swift Testing.

First, we’ll have 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 have a look at leveraging continuations in your unit assessments to check completion handler primarily based code.

Testing async code with Swift Testing’s confirmations

I’ll begin this part by stating that the primary purpose that I’m overlaying affirmation is that it’s current within the framework, and Apple suggests it as an possibility 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 usually.

With that mentioned, let’s see what affirmation can do for us.

Typically 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 needs to be despatched down an AsyncStream.

As normal with unit testing, we’re not going to actually care in regards to the precise particulars of our occasion supply mechanism.

In actual fact, I’ll present you the way that is performed with a closure as a substitute of an async for loop. Ultimately, the small print right here don’t matter. The primary factor that we’re serious about proper now’s 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 below are among the guidelines that we need to check:

  • Our object has an async methodology referred to as createFile that kicks of a course of that includes 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 is named for each accomplished step of our course of.

The onStepCompleted closure will obtain one argument; the finished step. This shall be a worth of kind FileCreationStep:

enum FileCreationStep {
  case fileRegistered, uploadStarted, uploadCompleted
}

With out affirmation, we will write our unit check for this as follows:

@Take a look at("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)
  })

  attempt await supervisor.createFile()
  #count on(completedSteps == [.fileRegistered, .uploadStarted, .uploadCompleted])
}

We are able to additionally refactor this code and leverage Apple’s affirmation method to make our check look as follows:

@Take a look at("File creation ought to undergo all three steps earlier than finishing")
func fileCreation() async throws {
  attempt await affirmation(expectedCount: 3) { verify in 
    var expectedSteps: [FileCreationStep] = [.fileRegistered, .uploadStarted, .uploadCompleted]

    let supervisor = RemoteFileManager(onStepCompleted: { step in
      #count on(expectedSteps.removeFirst() == step)
      verify()
    })

    attempt await supervisor.createFile()
  }
}

As I’ve mentioned 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.

Notice that we name the affirmation with attempt await.

Which means that our check is not going to full till the decision to our affirmation completes.

We additionally move 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 attempt await supervisor.createFile(). This kicks off the method and in my onStepCompleted closure I confirm that I’ve obtained the correct 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 whenever you need to check code that’s absolutely completion handler primarily based since that might imply that the closure returns earlier than you possibly can name your affirmation the anticipated variety of occasions.

Right here’s an instance:

@Take a look at("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 move no anticipated depend. Which means that our verify ought to solely be referred to as as soon as.

Within the closure, I’m operating my completion handler primarily based 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 primarily based 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 primarily based code in Swift Testing.

Testing completion handlers with continuations

Swift concurrency comes with a function referred to as continuations. If you’re not aware of 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’ll assume that you already know continuations fundamentals. I’ll simply have a look at how they work within the context of Swift testing.

The issue that we’re attempting to resolve is actually that we are not looking for our check perform to return till our completion handler primarily based 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 look ahead to a continuation. Within the continuation, we will name our completion handler primarily based APIs after which resume the continuation when our callback is named and we all know that we have performed all of the work that we have to do. Let’s examine what that appears like in a check.

@Take a look at("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 to be similar to the check that you simply noticed earlier than, however as a substitute of ready for a affirmation, we’re now calling the withCheckedContinuation perform. Within the closure that we handed to that perform, we carry out the very same work that we carried out earlier than.

Nonetheless, 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.

Once you’re testing completion handler primarily based code, I normally discover that I’ll attain for this as a substitute 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’ve got realized that Apple’s really useful method for testing closure primarily based asynchronous code is with confirmations. Nonetheless, 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 at all times the case.

Then I confirmed you that if you wish to check a extra conventional completion handler primarily based API, which might be what you are going to be doing, you need to be utilizing continuations as a result of these enable our assessments to droop.

We are able to resume a continuation when the asynchronous work that we had 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.

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 
rooshohttps://www.roosho.com
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here


Latest Articles

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog.