Unit test to call REST API

I have been trying to test function that has a network call request with alamofire, using the dispatchqueue. I am having a problem making the function wait for the execution of the network request. The test simply runs asynchronously without waiting for the network call.

Following is the code with which i tried



func testLoginAg(){

let dispatchQueue = DispatchQueue(label: "QueueIdentification", qos: .background)

dispatchQueue.async{

let username = "someemail@xyz.com"

let password = "xxxxxxxxx"

let headers = ["Content-Type": "application/json"]

print("background")

let params : [String : Any] = ["API_KEY" : "XXXX", "username" : username, "password":password]

let url = MyVariables.baseUrl + "/api/login"

self.sut.login(url: url, parameters: params, headers: headers)


}

DispatchQueue.global(qos: .userInteractive).async {


XCTAssertNotEqual(sut.abc, true)

for i in 11...20{

print(i)

}

}

}

Here the login function consists of the network request. The variable abc is set inside the login function after the network request call. Now how can i execute " XCTAssertNotEqual(sut.abc, true)" only after the completion of login function.


Replies

XCTest has some feature for testing asynchronous operations.


Check this article:

Testing Asynchronous Operations with Expectations