Skip to content

Instantly share code, notes, and snippets.

@rajohns08
Last active April 8, 2021 22:50
Show Gist options
  • Save rajohns08/02bd0d34f15670bdf931 to your computer and use it in GitHub Desktop.
Save rajohns08/02bd0d34f15670bdf931 to your computer and use it in GitHub Desktop.
iOS / Swift - Unit test for verifying text field limit not exceeded
func testTextFieldLimit() {
// Set up view before interacting with the text field
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))
let vc = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
vc.loadView()
// Test maximum number of allowable characters
let atTheLimitString = String(count: maxNumCharacters, repeatedValue: Character("a"))
let atTheLimitResult = vc.textField(vc.textField, shouldChangeCharactersInRange: NSRange(location: 0, length: 0), replacementString: atTheLimitString)
XCTAssertTrue(atTheLimitResult, "The text field should allow \(maxNumCharacters) characters")
// Test one more than the maximum number of allowable characters
let overTheLimitString = String(count: maxNumCharacters+1, repeatedValue: Character("a"))
let overTheLimitResult = vc.textField(vc.textField, shouldChangeCharactersInRange: NSRange(location: 0, length: 0), replacementString: overTheLimitString)
XCTAssertFalse(overTheLimitResult, "The text field should not allow \(maxNumCharacters+1) characters")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment