1

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!

Jon Reid
  • 20,545
  • 2
  • 64
  • 95
Caleb
  • 295
  • 3
  • 15
  • When unit testing you are testing small units.. you need to call the button selector yourself to mimic button taking and then check whether your alert has been initialised or not. – Harsh Mar 16 '18 at 13:31
  • Thanks for your response, yes. but is there is anyway to handle IBAction function for button with Unit test class itself.. – Caleb Mar 16 '18 at 13:41
  • You can go through the link https://stackoverflow.com/questions/18699524/is-it-possible-to-test-ibaction – Harsh Mar 16 '18 at 13:48
  • Would you like Swift or Objective-C? – Jon Reid Mar 17 '18 at 18:03
  • Yes, I am coding swift, button action calling from controller but, i could not able to test Alert showing or not..Do you know how to check Alerts is displaying or not in unit test. – Caleb Mar 19 '18 at 05:16

1 Answers1

4

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
}
Jon Reid
  • 20,545
  • 2
  • 64
  • 95
  • Thanks a lot, great solution with amazing explanation you saved my time.it worked nicely. – Caleb Mar 20 '18 at 10:37