Reputation: 1468
My app is using Alamofire to send http request and wanna write some unit test for this part. I have created some json file as response. How can I block the Alamofire request and let Alamofire to return the content in json file as response? Can we use method swizzling to replace the function?
Upvotes: 1
Views: 2478
Reputation: 12770
Use a framework like OHHTTPStubs to stub you network requests or make real network requests. In either case, XCTest
has a variety of methods for asynchronous waiting, like XCTExpectation
s.
Upvotes: 2
Reputation: 1015
This is how you wait for some asynchronous callbacks. This is bare minimum test. You can improve it more for your test requirement
func testCheckThatTheNetworkResponseIsEqualToTheExpectedResult() {
//expected result
let expectedResult: [String:Any] = ["data":"somedata","order_number":2]
let expectations = expectation(description: "The Response result match the expected results")
if let requestUrl = URL(string: "some url to fetch data from") {
let request = Alamofire.request(requestUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
request.responseJSON(completionHandler: { (response) in
switch response.result {
case .success(let result):
//do the checking with expected result
//AssertEqual or whatever you need to do with the data
//finally fullfill the expectation
expectations.fulfill()
case .failure(let error):
//this is failed case
XCTFail("Server response failed : \(error.localizedDescription)")
expectations.fulfill()
}
})
//wait for some time for the expectation (you can wait here more than 30 sec, depending on the time for the response)
waitForExpectations(timeout: 30, handler: { (error) in
if let error = error {
print("Failed : \(error.localizedDescription)")
}
})
}
}
Upvotes: 2