How do i mock a method that accepts a handle as an argument in OCMock?

早过忘川 提交于 2019-12-03 11:03:09

Sadly, I haven't found a good solution for this either. The best I can say is to try to make the use of the NSError** as small as possible, and then put it in an isolated function that you can completely mock out on your partial mock.

I'm finding that any code that uses anything other than an NSObject* (or derived) or primitive values (NSInteger, BOOL, etc) is pretty much impossible to test using OCMock.

[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg setTo:nil]];

or

NSError* someError = ...
[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg setTo:someError]];

You could also do

[[[mock stub] andReturn:someDict] uploadValues:YES error:[OCMArg anyPointer]];

but this might cause your code to incorrectly think that you passed back a real NSError.

With ARC, your method declaration will probably look like this:

- (NSDictionary *) uploadValues:(BOOL)doSomething error:(NSError *__autoreleasing *)error;

Here is how I mock these types of methods:

BOOL mockDoSomething = YES;

NSError __autoreleasing *error = nil;

[[[mock stub] andReturn:someDict] uploadValues:OCMOCK_VALUE(mockDoSomething) error:&error];
NSError *__autoreleasing *err = (NSError *__autoreleasing *) [OCMArg anyPointer];

[[[_mockReporter stub] andReturnValue:OCMOCK_VALUE((BOOL){YES})]
   yourMethodCall:err];

I created a category on OCMArg to aid with this situation.

OCMArg+Helpers.h:

@interface OCMArg (Helpers)

+ (NSError *__autoreleasing *)anyError;

@end

OCMArg+Helpers.m:

@implementation OCMArg (Helpers)

+ (NSError *__autoreleasing *)anyError {
    return (NSError *__autoreleasing *)[OCMArg anyPointer];
}

@end

Then, whenever I have an error param I need to mock, use anyError, like so:

[[myMock stub] someMethodWithArg:anArg error:[OCMArg anyError]];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!