如何在iOS Swift中制作登录屏幕的单元测试用例 [英] How can i make unit test cases of Login screen in iOS swift

查看:160
本文介绍了如何在iOS Swift中制作登录屏幕的单元测试用例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在登录"屏幕上遇到问题.如何使用登录屏幕制作单元测试用例?我有一个带有操作按钮的用户名和密码屏幕.我需要在单击按钮时调用API并进行一些单元测试用例.请向我提供一些信息.预先感谢.

I am having an issue on the logIn screen. how can I make a unit test case with a login screen? I have username and password screen with an action button. I need to call an API when clicking on a button and make some unit test cases. Please provide me some information. thanks in advance.

推荐答案

最简单的方法是对代码进行结构化,以使其实际上不会启动登录API调用.而是:

The simplest approach is to structure your code so that it doesn't actually initiate the login API call. Instead, it:

  • 创建请求,但在发送之前停止
  • 处理响应

然后,您可以测试填充字段并点击按钮是否创建了正确的请求.之后,您可以测试各种响应,包括在端到端测试中难以创建的各种错误情况.

Then you can test that filling in the fields and tapping the button creates the correct request. After that, you can test various responses, including all sort of error cases that are hard to create in end-to-end testing.

要在单元测试中点击一个按钮,请使其进行测试,以便测试可以访问该按钮.然后呼叫sendActions(for: .touchUpInside)

To tap a button from a unit test, make it so that the test can access the button. Then call sendActions(for: .touchUpInside)

进一步阅读: iOS单元测试示例:使用Swift的XCTest技巧和技术

Further reading: iOS Unit Testing by Example: XCTest Tips and Techniques Using Swift

示例:有许多方法可以构造此结构.假设我们有一个协议

Example: There are many ways to structure this. Let's say we have a protocol

protocol NetworkCalling {
    typealias CallResult = Result<(Data, URLResponse), Error>
    typealias CompletionHandler = (CallResult) -> Void

    func call(request: URLRequest, completionHandler: @escaping CompletionHandler)
}

我们的视图控制器将使用给定的任何值.不在乎.它只是知道如何通过其属性来创建URLRequest.它还知道如何处理结果,无论成功与失败.

Our view controller will use whatever it's given. It doesn't care. It just knows how to make a URLRequest from its properties. It also knows how to handle the result, for both success and failure.

class ViewController: UIViewController {
    var networkCall: NetworkCalling?

    @IBAction private func login(sender: AnyObject) {
        let request = URLRequest(url: URL(string: "http://foo.bar?baz")!)
        networkCall?.call(request: request) { [weak self] result in
            self?.handleResult(result)
        }
    }

    private func handleResult(_ result: NetworkCalling.CallResult) {
        switch result {
        case let .success(data, response):
            break
        case let .failure(error):
            break
        }
    }
}

该协议引入了边界.视图控制器看不到该边界.这与视图控制器无关.该协议使我们有机会提供不同的实现者:

The protocol introduces a boundary. The view controller can't see past that boundary. It's not the view controller's business. The protocol gives us opportunities to provide different implementers:

  • 进行真正的网络通话的东西.
  • 包装另一个实现者的装饰器,进行日志记录.
  • 一个测试间谍,捕获其参数以进行单元测试.
  • 一种伪造的文件,用于重放存储的响应以进行UI测试.这使UI测试更快,更可靠.

这篇关于如何在iOS Swift中制作登录屏幕的单元测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆