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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…