Randy
Randy

Reputation: 4525

Method is not called with OCMClassMock

Hi there,

I am writing unit tests with OCMock and I am unable to understand why the following test fails. I am trying to test this method from a class called MyOtherViewController :

// private method of firstViewController
- (void)goToInitialViewController
{
    // type of secondViewController is SecondViewController
    [secondViewController showInitialViewController];
}

Here the test I wrote :

- (void)testShowInitialVCCalledWhenGoToInitialVCCalled
{
    id secondVCMock = OCMClassMock([SecondViewController class]);

    FirstViewController *firstVC = [FirstViewController new];

    [firstVC goToInitialViewController];

    OCMVerify([secondVCMock showInitialViewController]);
}

I also trying using OCMPartialMock([SecondViewController new]) but the test still fails. I thing I am missing something concerning mocks.

Any help would be appreciated ! Thanks

Upvotes: 0

Views: 249

Answers (1)

Jon Reid
Jon Reid

Reputation: 20980

secondViewController is an actual SecondViewController. For testing, you'll want to inject a replacement. There are several different ways, but the two cleanest are:

  1. Constructor injection: Pass in the second view controller to the initializer of the first view controller. Production code will pass in a SecondViewController. Test code will pass in a mock object.
  2. Property injection: Expose secondViewController as a property. Production code can set the property to a SecondViewController before the first view controller is presented. Test code can set it to a mock object.

For more, see How to Use Dependency Injection to Make Your Code Testable

Upvotes: 1

Related Questions