I'm testing a function that presents a UIAlertController, but the test keeps failing. This is what the function looks like:
func presentBuyingErrorDialogue() {
let alert = UIAlertController(
title: "Warning",
message: "Error purchasing item, please retry this action. If that doesn't help, try restarting or reinstalling the app.",
preferredStyle: .alert
)
let okButton = UIAlertAction(title: "OK", style: .default)
alert.addAction(okButton)
self.present(alert, animated: true, completion: nil)
}
Since this function is in a class called ShopViewController, I'm assuming that the correct way to test this would be to call the function shopViewController.presentBuyingErrorDiaologue()
then use XCTAssertTrue(shopViewController.presentedViewController is UIAlertController)
. However, the assert statement fails when I run the test. What would be the correct way to test that the UIAlertController is the presented view?
You should wait that UIAlertController
is fully presented before testing its visibility, so you might try to change your test following this way:
import XCTest
class UIAlertControllerTests: XCTestCase {
func presentBuyingErrorDialogue() {
let alert = UIAlertController(title: "Warning", message: "Error purchasing item, please retry this action. If that doesn't help, try restarting or reinstalling the app.", preferredStyle: .alert)
let okButton = UIAlertAction(title: "OK", style: .default)
alert.addAction(okButton)
UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: nil)
}
func testPresentBuyingErrorDialogue() {
self.presentBuyingErrorDialogue()
let expectation = XCTestExpectation(description: "testExample")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
XCTAssertTrue(UIApplication.shared.keyWindow?.rootViewController?.presentedViewController is UIAlertController)
expectation.fulfill()
})
wait(for: [expectation], timeout: 1.5)
}
}
You may change UIApplication.shared.keyWindow?.rootViewController
with your ShopViewController
.
import ViewControllerPresentationSpy
shopViewController.presentBuyingErrorDialogue()
Then call its verify
method:
alertVerifier.verify(
title: "Warning",
message: "Error purchasing item, please retry this action. If that doesn't help, try restarting or reinstalling the app.",
animated: true,
presentingViewController: shopViewController,
actions: [
.default("OK"),
]
)
This checks:
shopViewController
..alert
(by default)In addition to capturing values, AlertVerifier lets you easily execute the action for an alert button:
func test_alertOKButton() throws {
shopViewController.presentBuyingErrorDiaologue()
try alertVerifier.executeAction(forButton: "OK")
// Test the results here
}
The tests don't require any waiting for expectations, so they are super-fast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With