2

I want to stub [[NSProcessInfo processInfo] operatingSystemVersion] to take any OS version.

id processInfoMock = OCMClassMock([NSProcessInfo class]);
[OCMStub([processInfoMock operatingSystemVersion]) andReturnValue:NULL];
NSOperatingSystemVersion osVersion = [[NSProcessInfo processInfo] operatingSystemVersion];

But iOS simulator's OS version is returned. Is it possible to stub NSProcessInfo methods? And, Is it appropriate to stub Foundation's classes?


[UPDATED] With Erik's advice, the issue is solved. I needed to stub processInfo class method to return a mock instance of NSProcessInfo. Here is test-passed code:

// Prepare fakeVersion instead of NULL.
NSOperatingSystemVersion fakeVersion = {0,0,0};
// Mock NSProcessInfo.
id processInfoMock = OCMClassMock([NSProcessInfo class]);
// Stub processInfo class method to return the mock instance.
[OCMStub([processInfoMock processInfo]) andReturn:processInfoMock];
// Stub operatingSystemVersion instance method to return fakeVersion.
[OCMStub([processInfoMock operatingSystemVersion]) andReturnValue:OCMOCK_VALUE(fakeVersion)];

// Another solution using OCMPartialMock.
// Partial mock for NSProcessInfo instance.
id processInfo = [NSProcessInfo processInfo];
id processInfoPartialMock = OCMPartialMock(processInfo);
// Stub operatingSystemVersion instance method to return fakeVersion.
[OCMStub([processInfoPartialMock operatingSystemVersion]) andReturnValue:OCMOCK_VALUE(fakeVersion)];
Keita
  • 1,478
  • 2
  • 14
  • 18

1 Answers1

2

You have to make sure that the mock is actually used by stubbing the processInfo class method. This is shown in the section titled "Creating stubs for instance and class methods" on the front page of the OCMock website.

By the way, why mix different syntactical styles? Why not just write

OCMStub([processInfoMock operatingSystemVersion]).andReturn(NULL);
Erik Doernenburg
  • 2,933
  • 18
  • 21
  • Thanks @erik-doernernburg for your comment. As you mentioned, the problem was I needed to stub `processInfo` class method of `NSProcessInfo` to return the mock instance. I will update my question to add test passed code. – Keita Feb 04 '16 at 19:49
  • About syntax andReturn is not available in my Xcode for some reason. It suggests _andReturn method, which expects a NSValue parameter. I use OCMock 3.2. Do you know what a problem could be? – Keita Feb 04 '16 at 19:50