Search code examples
iosobjective-ctddocmockito

OCMockito stub singleton shared instance method


I was using OCMock for stubbing class lvl methods and it worked well. Now I need to achieve the same behaviour with OCMockito.

In OCMock I have following:

_mock = mockClass([MySingleton class]);
OCMStub([_mock sharedSingleton]).andReturn(_mock);

In my case I have to stub sharedSingleton method because it is used in multiple places during tests.


Solution

  • OCMock's ability to directly stub singletons is done through method swizzling. For OCMockito, I purposely avoid this approach. I recommend you use some form of Dependency Injection to provide the instance.

    If you don't want that, you can always intermix OCMock and OCMockito. That way you can continue to have the OCMock behavior, while using OCMockito for other things.