How to add tap action for button in “Unit Testing” and show Alert

独自空忆成欢 提交于 2019-12-13 08:03:40

问题


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!


回答1:


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:

  • To test a button action, unit tests can invoke sendActions(for: .touchUpInside)
  • To test standard alerts, use ViewControllerPresentationSpy.

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

let alertVerifier = AlertVerifier()

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

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
}


来源:https://stackoverflow.com/questions/49321917/how-to-add-tap-action-for-button-in-unit-testing-and-show-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!