Search code examples
iosxcode5uitextfielduitextfielddelegate

Unit Testing UITextField Method


I'm very much new to iPhone app development, so starting with some unit testing. Pardon me if it is trivial question.

I have following code for a text field,

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    //Check whether currently editing text field is a account name text field
    if([[_customCellObjects objectAtIndex:0] textField] == textField) {
        NSUInteger newLength = [[[_customCellObjects objectAtIndex:0] textField].text length] + [string length] - range.length;

         //Return NO(Non Editable) if the account name text field exceeds more than 50 characters
         return (newLength > 50) ? NO : YES;
    }
    else {
        //Return YES(Editable) for the other text fields
        return YES;
    }
}

How to invoke the above method with XCTest? and how to pass parameters to it?


Solution

  • What I do for UITableViews is expose the table view as a property, then call the delegate/data source functions directly and check the desired output.

    In your case you would create a textField property that returns [[_customCellObjects objectAtIndex:0] textField] Or expose _customCellObjects

    YourViewController *vc = [[YourViewController alloc] init];
    bool result = [vc textField:vc.textField shouldChageCharactersInRange:NSMakeRange(0,1) replacementString: "a"]l
    
    XCTAssertTrue(result);
    

    The only thing I don't like about this is exposing the UITextField (or UITableView) unnecessarily. But others may post better options.