ios - 如何在 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 无关,但第二次永远不会失败。
解决方案
虽然我知道 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)
}
}
推荐阅读
- repmgr - 在 Debian 上设置 repmgr 见证节点
- python - selenium send_keys() 消息:元素不可交互
- matplotlib - Seaborn lineplot:注释最后一个值
- php - 在 Wordpress 中按日期过滤最新的帖子
- javascript - 如何在不刷新的情况下获得更新的时间
- javascript - 跨多个模式引用相同的 json 对象
- python-3.x - 在 Django Rest Framework 中订购?
- python - 与 Instagram 上的评论互动的问题
- javascript - 带有实时流嵌入的 iframe 音频无法正常工作(缩放)
- oracle - 两个列表之间的 IN 运算符在 oracle 中不起作用