【问题标题】:Unit Testing a method that uses REST calls in Swift单元测试在 Swift 中使用 REST 调用的方法
【发布时间】:2016-09-22 14:27:15
【问题描述】:

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

我正在开发一个正在为其编写单元测试的项目,但在解决问题时遇到了一些麻烦。

我正在测试的方法利用 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”似乎超出了范围,所以我被困在了

使用未解析的标识符“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.

【问题讨论】:

    标签: json swift rest unit-testing


    【解决方案1】:

    您的代码的前几个问题

    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() // 告诉进程完成

    waitForExpectationsWithTimeout(5){} //告诉等待 5 秒或抛出错误

    了解更多info

    【讨论】:

    • 我想这正是我需要的katch!谢谢!
    • 快速跟进,我应该像这样设置我的单元测试吗?我读过这在技术上是集成测试而不是单元测试。我应该使用本地文件来避免依赖对服务器的调用吗?我只是问你是否碰巧知道。否则,我会继续做更多的研究。再次感谢!
    • 我认为这是一个单独的问题。但我会推荐离线和在线。离线使用 json 文件等 & 在线使用实际调用
    • 你可以从这里开始blog.carbonfive.com/2012/07/09/fixture-data-for-ios-tests离线。我现在正在处理它,所以如果我有准备好的东西我会上传到 github 上展示
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多