Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set readonly navigationController property on UIViewController for mocking

I have created a mock UINavigationController using OCMock. However, I cannot assign it to the navigationController property of a UIViewController since that property is readonly.

id mockNavController = [OCMockObject mockForClass:[UINavigationController class]];
...
myViewController.navigationController = mockNavController; // readonly!

The author of this blog post claims to have found a solution but neglected to share it.

like image 800
titaniumdecoy Avatar asked Dec 22 '10 23:12

titaniumdecoy


1 Answers

It's not necessary to create a mutator that allows you to set the navigationController property, as you can mock the accessor that returns it. Here's how I do it:

-(void)testTappingSettingsButtonShouldDisplaySettings {
    MyController *myController = [[MyController alloc] init];

    // expect the nav controller to push a settings controller
    id mockNavigationController = [OCMockObject mockForClass:[UINavigationController class]];
    [[mockNavigationController expect] pushViewController:[OCMArg any] animated:YES];

    // set up myController to return the mocked navigation controller
    id mockController = [OCMockObject partialMockForObject:myController];
    [[[mockController expect] andReturn:mockNavigationController] navigationController];

    [myController settingsButtonTapped];

    [mockNavigationController verify];
    [mockController verify];
    [myController release];
}
like image 93
Christopher Pickslay Avatar answered Nov 15 '22 19:11

Christopher Pickslay