iPhone testing: testing IBOutlets

| | August 7, 2015

I actually feel a little embarrassed asking this because it feels about as basic as you can go, but it’s been stumping me for hours…

Let’s say I have an instance of a UIViewController (called MyViewController) which simply has one IBOutlet to a UITextField, and when the page loads I either set it to be Enabled or not based on a BOOL property.

- (void)viewDidLoad {
    [super viewDidLoad];
    self.surname.enabled = self.allowTextField;
}

Everything is wired up correctly and when I run the app it works as expected (lord – I’d hope so cause if I couldn’t get that part right, I probably shouldn’t be writing iPhone apps…).

Anyway, I decided to be diligent and write application Unit Tests for the app because it’s something I want to become a lot more solid in. Unfortunately, I cannot for the life of me understand why the following does not work…

-(void)testFieldEnabled {
    MyViewController *myController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
    myController.allowTextField = YES;
    [myController viewDidLoad];
     STAssertTrue(myController.surname.enabled, @"Why is this not correct?");
}

I’ve kept this example extremely simple because I truly don’t get why this is not working and believe it must be due a major failing in my understanding of unit testing. Shouldn’t the above unit test fire-up an instance of MyViewController page, set the property, run the method and return true? At the moment it keeps telling me that the surname textfield is not enabled.

Thanks for your help and a happy new year to you all!

3 Responses to “iPhone testing: testing IBOutlets”

  1. You can use ‘load View’ instead of view did Load. You also have to describe ‘load View’ in My View Controller

  2. Try the following:

    -(void)testFieldEnabled {
       MyViewController *myController = [[MyViewController alloc] initWithNibName:nil bundle:nil];
       [myController view];
       myController.allowTextField = YES;
       STAssertTrue(myController.surname.enabled, @"Why is this not correct?");
    }
    

    viewDidLoad will only call your delegate method having your initialization code. It won’t do any actual loading of view.
    Additionally, you need to set allowTextField after loading the view, as it would, otherwise, override it with the default value.

  3. This is because calling viewDidLoad manually doesn’t actually load the view. You should call view property of the view controller, which will load the view automatically (or call loadView manually).

Leave a Reply