Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

ios - How to add tap action for button in "Unit Testing" and show Alert

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...