1

I have following code to test if view is properly configured(among others, I have the monthScrollview placed as a subview of view:

@implementation ECBrowserViewControllerTests
-(void)setUp
{
  //-deviceSpecific simply adds suffix like '_iPad'
  main=[[ECBrowserViewController alloc] initWithNibName:[@"ECBrowserViewController" deviceSpecific] bundle:nil];
}
-(void)testOutlets
{
    STAssertNotNil(main.view, @"View outlet not set!");

    STAssertNotNil(main.monthScrollView, @"no month scrollview");
    STAssertTrue(main.monthScrollView.pagingEnabled, @"Paging should be enabled");
}

-(void)testPaging
{
    STAssertNotNil(main.monthScrollView, @"no month scrollview");
    STAssertTrue(main.monthScrollView.pagingEnabled, @"Paging should be enabled");
}
@end

Could any one tell me why the testPaging fails, while testOutlets succeeds? I figured out that's about checking the parentView first, but why?

I'm using Xcode 4.6.3 and builtin SenTestingKit

Michał Zygar
  • 4,052
  • 1
  • 23
  • 36

2 Answers2

4

It simply fails because ViewController's views in COCOA are loaded lazily: The view property is not set until it's needed, namely when one tries to fetch its value for the first time. At that moment loadView is summoned.

The reason why your testPaging test fails is due to the fact that the viewController's view in never fetched.

So, in your specific test, you have to explicitly invoke -view over a the view controller in order to have its -loadView method/callback summoned and hence get its view (and subviews) allocated.

HepaKKes
  • 1,555
  • 13
  • 22
  • Awesome answer! Do you have a reference that says the views are loaded lazily? – H.Rabiee Nov 08 '15 at 12:51
  • Thank you, I remember reading it either on Apple's documentation about view controllers or on some books (Unfortunately I can't remember which one). Anyway it's quite easy to prove view controller's views lazy loading by writing some code and running some tests. – HepaKKes Nov 08 '15 at 13:02
0

Try this:

-(void)testPaging
{
    [main view];    // Force nib to load

    STAssertNotNil(main.monthScrollView, @"no month scrollview");
    STAssertTrue(main.monthScrollView.pagingEnabled, @"Paging should be enabled");
}
Jon Reid
  • 20,545
  • 2
  • 64
  • 95