【发布时间】:2019-04-07 13:16:02
【问题描述】:
我有一个登录视图控制器,用户使用 Almofire 库来获取响应。我在该控制器上进行单元测试,但测试总是失败。我想是因为需要时间来回应。
我的测试用例:
override func setUp() {
super.setUp()
continueAfterFailure = false
let vc = UIStoryboard(name: "Main", bundle: nil)
controllerUnderTest = vc.instantiateViewController(withIdentifier: "LoginVC") as! LoginViewController
controllerUnderTest.loadView()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
controllerUnderTest = nil
super.tearDown()
}
func testLoginWithValidUserInfo() {
controllerUnderTest.email?.text = "raghad"
controllerUnderTest.pass?.text = "1234"
controllerUnderTest.loginButton?.sendActions(for: .touchUpInside)
XCTAssertEqual(controllerUnderTest.lblValidationMessage?.text , "logged in successfully")
}
我尝试使用:
waitForExpectations(timeout: 60, handler: nil)
但是我收到了这个错误:
捕获“NSInternalInconsistencyException”
登录演示器中的almofire功能:
func sendRequest(withParameters parameters: [String : String]) {
Alamofire.request(LOGINURL, method: .post, parameters: parameters).validate ().responseJSON { response in
debugPrint("new line : \(response)" )
switch response.result {
case .success(let value):
let userJSON = JSON(value)
self.readResponse(data: userJSON)
case .failure(let error):
print("Error \(String(describing: error))")
self.delegate.showMessage("* Connection issue ")
}
self.delegate.removeLoadingScreen()
//firebase log in
Auth.auth().signIn(withEmail: parameters["email"]!, password: parameters["pass"]!) { [weak self] user, error in
//guard let strongSelf = self else { return }
if(user != nil){
print("login with firebase")
}
else{
print("eroor in somthing")
}
if(error != nil){
print("idon now")
}
// ...
}
}
}
func readResponse(data: JSON) {
switch data["error"].stringValue {
case "true":
self.delegate.showMessage("* Invalid user name or password")
case "false":
if data["state"].stringValue=="0" {
self.delegate.showMessage("logged in successfully")
}else {
self.delegate.showMessage("* Inactive account")
}
default:
self.delegate.showMessage("* Connection issue")
}
}
我该如何解决这个问题? :(
【问题讨论】:
-
首先要确保满足您的期望。您的登录视图控制器中可能有一些完成处理程序。在您的测试中,等待该处理程序触发并调用
expectation.fulfill()。 -
我没听懂你的意思:(
-
好吧,在您的登录视图控制器中,您调用了异步运行的 Alamofire。像
Alamofire.request ... .response { ...这样的东西。当响应闭包中的代码执行时,您必须确保调用expectation.fulfill()。如果您可以在登录视图控制器中发布 Alamofire 调用,我可以为您提供更多帮助。 -
如果你没有达到预期,你就会陷入困境并且永远不会通过。
-
非常感谢您的帮助。我发布了我的 almofire 功能以了解:(
标签: swift unit-testing cocoapods xcode10.2