Search code examples
swiftxcode

How to test a method that contains Task Async/await in swift


Given the following method that contains a Task.

  • self.interactor is mocked.
func submitButtonPressed() {
    Task {
        await self.interactor?.fetchSections()
    }
}

How can I write a test to verify that the fetchSections() was called from that method?!

My first thought was to use expectations and wait until it is fulfilled (in mock's code).

But is there any better way with the new async/await?


Solution

  • Ideally, as you imply, your interactor would be declared using a protocol so that you can substitute a mock for test purposes. You then consult the mock object to confirm that the desired method was called. In this way you properly confine the scope of the system under test to answer only the question "was this method called?"

    As for the structure of the test method itself, yes, this is still asynchronous code and, as such, requires asynchronous testing. So using an expectation and waiting for it is correct. The fact that your app uses async/await to express asynchronousness does not magically change that! (You can decrease the verbosity of this by writing a utility method that creates a BOOL predicate expectation and waits for it.)