Add Tests for Alert Buttons

With the system under test now in the test fixture, we’ll have an easier time adding more tests for the alert buttons. Let’s add a test to execute the action for the OK button.

The AlertVerifier method executeAction(forButton:) throws an exception if it can’t find a button with the given name. So we have to precede it with a try statement. For this to work in a test, mark the test method as throws:

Alert/AlertTests/ViewControllerTests.swift
 func​ ​test_executeAlertAction_withOKButton​() ​throws​ {
 tap​(sut.button)
 
 try​ alertVerifier.​executeAction​(forButton: ​"OK"​)
 
 // Normally, assert something
 }
images/aside-icons/tip.png

If you need a try in test code, mark the test case as a throwing function with throws. Then if the call ever throws an exception, XCTest will report it as a test failure.

For our experiment, this test has no assertions. Run tests and find the console output (See Examine Console Output), where you will see the following.

 Test Case '-[AlertTests.ViewControllerTests
  test_executeAlertAction_withOKButton]' started.
 >> OK
 Test Case '-[AlertTests.ViewControllerTests
  test_executeAlertAction_withOKButton]' passed (0.015 seconds).

Write another test to execute the action for the Cancel button.