3

I'd like to test that outlets are setup correctly through XCTest. I'd like to share my current approach: allocate the VC programmatically and check that outlets are not nil. Something I thought should be straightforward, but the test is failing.

MyViewController *mvc = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:[NSBundle mainBundle]];

[mvc awakeFromNib];
XCTAssert([mvc tableViewOutlet], @"Table view should be hooked up");

I wonder if I'm missing something obvious?

H.Rabiee
  • 4,747
  • 3
  • 23
  • 35
  • It's possible that the main bundle of the test is different than the main bundle of the application, so it's not finding the NIB. – Charles A. Nov 08 '15 at 09:07
  • OK, but how come it's possible to allocate through initWithNibName? mvc is != nil just to clarify. What's the solution? Should I add the .xib in Copy Bundle Resources for the target? – H.Rabiee Nov 08 '15 at 12:23
  • You can pass nil for nib name and bundle and still get back a view controller, that init method never fails. – Charles A. Nov 08 '15 at 17:31

1 Answers1

3

According to this question XIB outlets unit testing

I found that NIBs are lazy loaded. You must call [mvc loadView] in order to connect all the outlets.

Community
  • 1
  • 1
H.Rabiee
  • 4,747
  • 3
  • 23
  • 35
  • 1
    NIBs are lazy loaded, but the appropriate way to load them is to access to `view` property, not call `loadView` directly, as the answer to that question indicates if you read it carefully. – Charles A. Nov 08 '15 at 17:32
  • In that case one would do [mvc.view subViews] and locate the tableView or the one that's under test, right? What if you want to test other objects in the nib that are not views, i.e array controllers? – H.Rabiee Nov 09 '15 at 11:21
  • 1
    Once you do force the load with `[mvc view];` you can then access your `IBOutlet`s as usual. I was just suggesting you use `[mvc view];` instead of `[mvc loadView];` because it invokes the view loading mechanism as it is normally intended to be invoked (typically you don't call loadView directly). – Charles A. Nov 09 '15 at 18:12