Frage

I am using XCTest to test my view controller.

I have to validate my textfield, so I initialized a view controller from my storyboard and tried to access the textfiled:

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController *vc = (ViewController *)[sb instantiateViewControllerWithIdentifier:@"ViewController"];
XCTAssertNotNil(_vc.emailField, @"email field is nil!"); // fail

I can access emailField and set/get value for it if I use simulator to test this view controller manually, but I can not access it through my code(_vc.emailField is nil).

I want to know:

  1. from the perspective of code, when will the elements in storyboard be created by iOS. (I guessed they would be created in viewDidLoad, but I found I was wrong after testing it)

  2. how can I access the elements in XCTest?

War es hilfreich?

Lösung

All of the view elements in the xib will be available after the view is loaded. The issue is that you are never actually causing the view to be loaded.

You should call viewController.view, which will cause the view to be loaded and all of the outlets to be connected up.

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ViewController *vc = (ViewController *)[sb instantiateViewControllerWithIdentifier:@"ViewController"];

__unused UIView *view = _vc.view; // cause the view to be loaded

XCTAssertNotNil(_vc.emailField, @"email field is nil!");

Andere Tipps

The properties should be created in viewDidLoad, but setting the actual text properties cannot be done until viewWillAppear:

The way I fix this problem is to add another property to the view controller to contain the data (as a view should not be the primary owner of any stored data anyway) and set the value of vc.emailField.text to that property in viewWillAppear

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top