Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccabanero/b88a77caba37f8dd9fbf to your computer and use it in GitHub Desktop.
Save ccabanero/b88a77caba37f8dd9fbf to your computer and use it in GitHub Desktop.
Sample iOS Unit Tests: Working with a ViewController that presents a UIAlertController
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