问题
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?
回答1:
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)
}
回答2:
Technically this is no unit test, but UI testing, because the behavior of your UI is no unit. But there is the ability to include UI testing in your tests, which will participate on the test chain.
Basically you get the UI element (XCUIElement
) you want to test and send actions to it, i. e. using -typeText:
. Then you compare the actual state of that element to the intended state using the XCUIElementAttributes
protocol.
Googling for the above identifiers will give you some details. However, the documentation is not that good.
来源:https://stackoverflow.com/questions/47389161/can-we-check-the-validation-of-uitextfield-while-unit-testing