我正在尝试使用Alamofire作为其余框架对我的API进行单元测试。我已经在Podfile中添加了pod依赖项和所有内容,关于丢失模块或其他内容没有错误。目前作为示例,我试图访问google主页,并在响应时尝试使用XCRAssertEqual评估响应代码。如果我在视图控制器中使用该函数,则该函数运行良好,但在测试类中却无法运行。通过不工作,我的意思是这两种情况都是正确的,因为两个响应代码都等于.success和.filure。这可能是什么原因?以下是我的TestClass,其中定义了函数以及正在使用该函数的测试用例类

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)
        }

    }

}


测试用例类

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)
        }
    }
}


第一个测试用例工作正常,因为它与Alamofire无关,但是第二个永远都不会失败。

最佳答案

尽管我知道Alamofire请求是异步的,但我并没有想到它可能无法通过我的测试用例。因此,您应该做的就是等待响应。为此,您需要使用XCTestCase随附的期望。因此,重写的代码将如下所示:

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)
    }
}

关于ios - 如何在Alamofire响应上XCTAssertEqual?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52004806/

10-14 21:40
查看更多