如何在“单元测试"中为按钮添加点击动作并显示警报 [英] How to add tap action for button in "Unit Testing" and show Alert

查看:19
本文介绍了如何在“单元测试"中为按钮添加点击动作并显示警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的登录表单编写一个单元测试用例,在这种情况下,如果用户名和密码为空,那么我们单击登录按钮它会显示警报,我想为此场景编写测试用例,对我来说按钮操作不起作用并且警报未在单元测试中显示,我一直在寻找解决方案,任何人都可以提供帮助..谢谢!

I am trying to write a unit test case for my Login Form, in this if Username and Password empty then we click login button it will show alert, i want to write testcases for this scenario, for me button action not working and alert not showing with unit testing , i am searching for solution long time any one could help..Thanks!

推荐答案

首先,我要说的是,您可以考虑禁用登录按钮,直到用户名和密码不为空.

First, let me say that rather than an alert, you might consider keeping the Log In button disabled until the User Name and Password are non-empty.

>

但是要回答您的问题:

But to answer your question:

  • 要测试按钮操作,单元测试可以调用 sendActions(for: .touchUpInside)
  • 要测试标准警报,请使用 ViewControllerPresentationSpy.

在出现任何警报之前,导入 ViewControllerPresentationSpy 并在您的测试中创建一个 AlertVerifier:

Import ViewControllerPresentationSpy and create an AlertVerifier in your tests before any alert is presented:

let alertVerifier = AlertVerifier()

然后调用可能会或可能不会出现警报的触发器.在您的情况下,这是按钮上的 .touchUpInside.

Then invoke the trigger that may or may not present an alert. In your case that's a .touchUpInside on the button.

您现在可以调用 verify 方法:

You can now call a verify method:

func test_tappingLoginButton_shouldPresentAlert() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let sut = storyboard.instantiateInitialViewController() as! ViewController
    sut.loadViewIfNeeded()
    let alertVerifier = AlertVerifier()

    sut.loginButton.sendActions(for: .touchUpInside)

    alertVerifier.verify(
            title: "Title",
            message: "Message",
            animated: true,
            presentingViewController: sut,
            actions: [
                .default("OK"),
            ]
    )
}

要测试显示警报,请使用

To test that an alert isn't presented, use

XCTAssertEqual(alertVerifier.presentedCount, 0)

要调用操作,请执行以下操作:

To invoke an action, do:

func test_showAlertThenTapOKButton() throws {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let sut = storyboard.instantiateInitialViewController() as! ViewController
    sut.loadViewIfNeeded()
    let alertVerifier = AlertVerifier()

    try alertVerifier.executeActions(forButton: "OK")

    // Check for expected results
}

这篇关于如何在“单元测试"中为按钮添加点击动作并显示警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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