vendredi 24 août 2018

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.

Aucun commentaire:

Enregistrer un commentaire