Last active
September 4, 2022 20:17
-
-
Save ccabanero/b88a77caba37f8dd9fbf to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: Working with a ViewController that presents a UIAlertController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func testControllerShowsAlertIfUserLogsInWithEmptyUsernameAndPasswordTextField() { | |
// mock of LoginViewController | |
class MockLoginViewController: LoginViewController { | |
var presentViewControllerTarget: UIViewController? | |
override func presentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { | |
presentViewControllerTarget = viewControllerToPresent | |
} | |
} | |
// instantiate MockLoginViewController and create TextFields | |
let mockLoginViewController = MockLoginViewController() | |
mockLoginViewController.userNameTextField = UITextField() | |
mockLoginViewController.passwordTextField = UITextField() | |
// TextFields have an empty state | |
mockLoginViewController.userNameTextField.text = String() | |
mockLoginViewController.passwordTextField.text = String() | |
// Tap login button when TextFields have empty state | |
mockLoginViewController.handleLogInTap(UIButton()) | |
// Assertions | |
let alertController = mockLoginViewController.presentViewControllerTarget as! UIAlertController | |
XCTAssertNotNil(alertController, "UIAlertController was not presented") | |
let expectedAlertTitle = "Oops!" | |
let actualAlertTitle = alertController.title | |
XCTAssertEqual(expectedAlertTitle, actualAlertTitle) | |
let expectedAlertMessage = "Please enter username and password." | |
let actualAlertMessage = alertController.message | |
XCTAssertEqual(expectedAlertMessage, actualAlertMessage) | |
let expectedActionNumber = 1 | |
let actualActionNumber = alertController.actions.count | |
XCTAssertEqual(expectedActionNumber, actualActionNumber) | |
let expectedActionTitle = "Ok" | |
let actualActionTitle = alertController.actions[0].title | |
XCTAssertEqual(expectedActionTitle, actualActionTitle) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment