首页 > 解决方案 > 如何在 Alamofire 响应上进行 XCTAssertEqual?

问题描述

我正在尝试使用 Alamofire 作为其余框架对我的 API 进行单元测试。我已经在 Podfile 中添加了 pod 依赖项和所有内容,并且没有关于缺少模块或其他内容的错误。目前作为一个例子,我正在尝试访问谷歌主页,并在响应时尝试使用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 无关,但第二次永远不会失败。

标签: iosswiftunit-testingtestingalamofire

解决方案


虽然我知道 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)
    }
}

推荐阅读