Suppose we have some validation in our ViewController
( say vc1 ) for a UItextfield
in shouldChangeCharactersInRange
method, as user only can enter the numbers not the alphabets or other special character.
I just want to know that in our XCTestCase
class, is this possible in unit testing, to check for a particular uitextfield
, is allowing some characters (in my case only numbers) or not?
Unit Testing is a type of software testing where individual units or components of a software are tested. The purpose is to validate that each unit of the software code performs as expected. Unit Testing is done during the development (coding phase) of an application by the developers.
Self-validating: Each test will have a single boolean output of pass or fail. It should not be up to you to check whether the output of the method is correct each time the test is run.
So, we can minimize the code, and manage it well, by creating an extension of UITextField . Then, inside it, create a function that will be used to validate the TextField . That function should return a Bool value, as shown below: This is just a custom validation; you can create a validation based on your needs.
Make unit tests that call shouldChangeCharactersInRange
and check the expectation that the result should be true, or false.
This is an example of how to unit test delegate methods. Where UIKit invokes a particular method, just have tests call the same thing.
Even though a particular class may implement the delegate method, it's better if the test remains ignorant of this. UIKit asks the text field for its delegate, then calls it. Our tests should do the same, and invoke through the delegate. Otherwise we are locking down the implementation, which would make it harder to refactor the delegate methods.
func testMyTextField_ShouldAllowAlphabeticCharacters() {
let vc = // …Whatever you do to load your view controller
vc.loadViewIfNeeded() // Make sure text field is loaded
let field = vc.myTextField
// Call through field.delegate, not through vc
let result = field.delegate.textField(field,
shouldChangeCharactersIn: NSMakeRange(0, 1),
replacementString: "a")
XCTAssertTrue(result)
}
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