简体   繁体   中英

How to XCTAssertEqual on Alamofire response?

I am trying to make unit testing for my API with Alamofire as the rest framework. I have added the pod dependencies and everything in the Podfile and there is no error regarding missing modules or something. Currently as an example I am trying to hit google homepage and on response I am trying to evaluate the response code with XCRAssertEqual . The function is working fine if I use in view controller but it's not working in test class. By not working I meant it's giving true for both cases, for both response code being equal to .success and .filure . What can be the reason of this? Below are my TestClass where function is defined and the test case class where it is being used

import Foundation
import Alamofire

class TestingClass {

    private init(){

    }

    static let sharedInstance = TestingClass()

    func getSquare(number:Int)->Int{
        return number * number
    }

    func getGoogleResponse(completion:@escaping (_ rest:Int)->Void){

        Alamofire.request("https://google.com").responseString { response in
            var result = -1
            switch response.result {
            case .success:
                result = 0
            case .failure(let error):
                result = 1
            }
            completion(result)
        }

    }

}

test case class

import XCTest
@testable import MyApp

class MyAppTests: XCTestCase {

    func testSquare(){
        XCTAssertEqual(TestingClass.sharedInstance.getSquare(number:2),6)
    }

    func testGoogle(){
        TestingClass.sharedInstance.getGoogleResponse { (res) in
            print("ANURAN \(res)")
            XCTAssertEqual(res, 0)
        }
    }
}

First test case is working fine as it has nothing to do with Alamofire but second time never fails.

Though I know Alamofire requests are asynchronous it did not hit my mind that it could fail my test case aslo. So what you should do is wait for the response. To do that you need to use expectation which comes with XCTestCase . So rewritten code will be like this:

import XCTest
@testable import MyApp

class MyAppTests: XCTestCase {

    func testSquare(){
        XCTAssertEqual(TestingClass.sharedInstance.getSquare(number:2),6)
    }

    func testGoogle(){
        let expectation = self.expectation(description: "Hitting Google")
        var result:Int?
        TestingClass.sharedInstance.getGoogleResponse { (res) in
            print("ANURAN \(res)")
            result=res
            expectation.fulfill()
        }
        wait(for: [expectation], timeout: 30)
        XCTAssertEqual(result!, 1)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM