Updated 26 October 2021
In the previous part, we have already know how to set up the unit testing in Xcode project & some basic functionality.
Refer: https://mobikul.com/unit-testing-in-ios-using-swift-part-1/
In this blog, we will discuss how to test the Network Call (Asynchronous function).
In-Network call we have to wait until the data will come to its totally Asynchronous function so that we have to wait in method until the result will come for that swift provide “expectation”
With the help of this, we can handle Network call.
Example:
1 2 3 4 5 |
let promise = expectation(description: "Completion handler invoked") wait(for: [promise], timeout: 5) // it helps to wait in thread. promise.fulfill() // it completes the overall thread. |
Here are Some Steps you need to follow this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import XCTest class CICDAPPTNetworkCall: XCTestCase { var sut: URLSession! override func setUp() { super.setUp() sut = URLSession(configuration: .default) } override func tearDown() { sut = nil super.tearDown() } } |
here we have taken the example through “URLSession”
Valid URL: https://itunes.apple.com/search?media=music&entity=song&term=abba
here we are checking the URL response is valid or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
func testCallToiTunesCompletes() { // given let url = URL(string: "https://itunes.apple.com/search?media=music&entity=song&term=abba") let promise = expectation(description: "Completion handler invoked") var statusCode: Int? var responseError: Error? // when let dataTask = sut.dataTask(with: url!) { data, response, error in statusCode = (response as? HTTPURLResponse)?.statusCode responseError = error promise.fulfill() } dataTask.resume() wait(for: [promise], timeout: 5) // then XCTAssertNil(responseError,"Any String Value") // it will pass when he get nil value nil == no issue XCTAssertEqual(statusCode, 200) // it compare the value if equal then no issue. } |
Here we have taken the “expectation” class to hold the network call response.
We have taken two Test checking method
1: XCTAssertNil(responseError,”Any String Value”) . if responseError returns nil then there is no issue.
2: XCTAssertEqual(statusCode, 200) if statusCode == 200 then no issue
if any matches fail then you will get the test fail result.
For checking the error case you just change the URL’s string or Invalid URL & check.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.