Search code examples
swiftxcodexctestcase

How to achieve asynchronous task dependency with XCTestCases?


I am writing some test cases for asynchronous operations where I have two operations on which unit test need to be performed.

Suppose I have some login webservice that need to called and on response of that another profile webservice should be called.

Is it possible to test above scenario using unit-testing in iOS?

Thank you in advance.


Solution

  • Yes it is actually quite easy, you use expectations to wait until a task(s) have been completed.

    Example:

    // Create an expectation for a background download task.
    let expectation = XCTestExpectation(description: "Login and fetch profile")
    
    MyApiClient.shared.login(username: username, password: password) { auth in
    
        // check login was successful before continuing
        MyApiClient.shared.fetchUserProfile(userId: auth.userId) { profile in 
    
            XCTAssertNotNil(profile)
    
            // Fulfill the expectation to indicate that the background task has finished successfully.
            expectation.fulfill()
        }
    }
    
    // Wait until the expectation is fulfilled, with a timeout of 10 seconds.
    wait(for: [expectation], timeout: 10.0)