json - 单元测试在 Swift 中使用 REST 调用的方法

标签 json swift rest unit-testing

首先让我声明我仍然不熟悉我正在尝试做的事情,但正在努力变得更好!

我正在从事一个项目,我正在为其编写单元测试,但我在解决问题方面遇到了一些麻烦。

我正在测试的方法利用 RESTAPI 调用来验证用户凭据。我不确定单元测试的最佳方法是什么。

这是我要为其进行单元测试的方法:

@IBAction func loginBtnActivate(sender: UIButton) {
    let enteredEmail: String = emailField.text!
    let enteredPassword: String = passwordField.text!
    let testInfo:[String: AnyObject] = ["User": enteredEmail, "Password": enteredPassword]
    RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
        if statusCode == 200 {
            let AuthToken: TokenObject = (TokenObject(json: json))
            try! self.keychain.set(AuthToken.Authorization, key:"Authorization")
            try! self.keychain.set(AuthToken.LifeTime, key: "LifeTime")
            try! self.keychain.set(AuthToken.UUID, key: "UUID")
             NSOperationQueue.mainQueue().addOperationWithBlock {
                self.performSegueWithIdentifier("loginToMyHealth", sender: nil)
            }
        } else if statusCode == 401 {
            self.incorrectLoginAlert()
        } else if statusCode == 503 {
            print("Service Unavailable Please Try Again Later")
        }
    }
}

这是我目前采用的方法:

 func testLoginInfoMatchesDataOnServer(){
    let enteredEmail: String = "user"
    let enteredPassword: String = "password"
    let testInfo:[String: AnyObject] = ["User": enteredEmail, "Password": enteredPassword]
    RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
    XCTAssert(statusCode == 200, "statusCode is not matching the server data")
}

我只是验证 Rest 调用是否成功以及凭据是否与 JSON 匹配。 XCTAssert 调用似乎没有正常工作。无论第一个参数是什么,XCTAssert 都不会影响测试是否成功。

例如,如果我输入:

XCTAssert(false, "statusCode is not matching the server data")

不管我输入什么,测试仍然会通过。如果我将 Assert 函数放在括号外,那么变量“statusCode”似乎超出了范围,所以我只能使用

Use of unresolved identifier 'statusCode'.

   func testLoginInfoMatchesDataOnServer(){
let enteredEmail: String = "user"
let enteredPassword: String = "password"
let testInfo:[String: AnyObject] = ["User": enteredEmail, "Password": enteredPassword]
RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
}
XCTAssert(statusCode == 200, "statusCode is not matching the server data")
}

我正在查看本指南以寻求帮助。对于我正在尝试做的事情,这会是更好的方法吗?

http://roadfiresoftware.com/2016/06/how-do-you-unit-test-rest-calls-in-swift/

同样,我对一些核心概念的理解可能完全不对,所以非常感谢您的建议!

提前致谢!

肖恩·W.

最佳答案

首先你的代码有几个问题

function test(){    
    RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in

    }//PostLogin call ends
    XCTAssert(statusCode == 200, "statusCode is not matching the server data") // Here StatusCode is not accessible as outside the block
}// end function

如果你想使用状态码你应该这样做

function test(){    
    RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
        XCTAssert(statusCode == 200, "statusCode is not matching the server data") // Here StatusCode is accessible inside the block
    }//PostLogin call ends
}// end function

但这会失败,因为您需要等待响应。这可以使用

来完成

waitForExpectationsWithTimeout(5)

所以正确的调用方式是——

function test(){    
    let URL = NSURL(string: "http://google.com/")!
    let expectation = expectationWithDescription("GET \(URL)")
    RestApiManager.sharedInstance.postLogin(testInfo) { (json, statusCode) in
        XCTAssert(statusCode == 200, "statusCode is not matching the server data") // Here StatusCode is accessible inside the block
        expectation.fulfill()
    }//PostLogin call ends
    waitForExpectationsWithTimeout(5){ error in 
        if let error = error {
            print("Error: \(error.localizedDescription)")
        }
    }//Wait block end
}// end function

这里重要的几行是

expectation.fulfill() // tells process is complete

waitForExpectationsWithTimeout(5){} //tells wait for 5secs or throw error

更多info

关于json - 单元测试在 Swift 中使用 REST 调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39641829/

相关文章:

javascript - 从这个 google places API 地址结果中提取地址片段的最佳方法是什么?

c# - 反序列化导致列表条目的副本

ios - Swift - 字典崩溃中的关闭

rest - 我应该何时从 REST 应用程序向客户端返回 HTTP 状态代码 500(内部服务器错误)?

python - Django 管理命令参数

java - WSO2 端口 8082 访问问题

PHP 无法检索大请求

mysql - GROUP_CONCAT 以多对多关系返回一个对象数组

ios - Swift sender.setTitle 代码不可见?

ios - 如何在添加为更多导航 Controller 的导航 Controller 上设置标题