2

Confused on OCMock for singleton, get two methods, but none of them is perfect in my opinion.

  1. Using partialMockForObject. I want to use partialMockForObject to do singleton class mock. See following code, it works well, but the defect is that singleton [NSNotificationCenter defaultCenter] will remember previous mock behavior, then when invoked in another place, it will crash, unexpected. So my question is that how can I create a method like "removeAllExpectations” to remove all remembered ones?

    id aMock = [OCMockObject partialMockForObject:[NSNotificationCenter defaultCenter]];

    [aMock expect] removeObserver:[OCMConstraint isKindOfClass:[WhereIsMyPhoneViewController class]]];

    [[aMock verify];

  2. Using category method. See http://twobitlabs.com/2011/02/mocking-singletons-with-ocmock/ mentions another method to do singleton mock, personally I prefer partialMockForObject, you don't need to mock all methods when unit testing.

Have sent my question to OCMock development group but no response got yet, need your smart guys opinion. Any idea or discussion will be appreciated, thanks in advance.

jianhua
  • 1,011
  • 1
  • 12
  • 28
  • I wish this question was actually answered, as this is exactly what I'd like to do in my test. Have 1 logical test instead of splitting up into 3+ tiny tests, and reset in-between. – SilverSideDown Feb 11 '13 at 21:47

2 Answers2

4

If you are using the lastest source code of OCMock (after 2012-04-06), call

[aMock stopMocking];

to reset the mocked object's state.

Hai Feng Kao
  • 5,219
  • 2
  • 27
  • 38
  • I don't see either stop or stopMocking referenced in any OCMock header. "-[NSProxy doesNotRecognizeSelector:stopMocking] called!" Are you guys sure these are supposed to work? – SilverSideDown Feb 11 '13 at 21:43
  • 1
    stopMocking is declared in OCMockObject.h – Hai Feng Kao Mar 06 '13 at 01:33
  • I checked again in the latest 2.0.1 framework download from http://ocmock.org/download/ and it's NOT there. But you're right, if I look at source at https://github.com/erikdoe/ocmock/blob/master/Source/OCMock/OCMockObject.h it's in there. So I guess I have to compile from source to get this to work. Thanks for the heads up. – SilverSideDown Mar 07 '13 at 14:53
1

You can call:

[aMock stop];

to reset the mocked object's state.

Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
  • Thanks you smart guy, the method inside library framework really works. – jianhua Dec 20 '11 at 02:27
  • Awesome, I was completely stumped with an inconsistency exception about a partial mock, and adding this to my tearDown method caused the exception/error to go away. Thank you! – kyleturner Aug 27 '12 at 16:12