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

查看:26
本文介绍了我如何在 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)

示例:有很多方法可以构建它.假设我们有一个协议

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天全站免登陆