Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we check the validation of uitextfield while Unit Testing?

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?

like image 775
iNoob Avatar asked Nov 20 '17 09:11

iNoob


People also ask

What is unit testing validation?

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.

What makes a unit test self validating?

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.

How do I validate in Swift?

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.


1 Answers

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)
}
like image 92
Jon Reid Avatar answered Sep 27 '22 16:09

Jon Reid