0

Consider this:

+(NSDictionary *)getDictionaryFromData:(id)data {
    @synchronized(self) {
        NSError *error = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
        if (error) {
            DLog(@"SERIALIZATION FAILED: %@", error.localizedDescription);
            return nil;
        }

        DLog(@"SUCCESS: %@", dict);
        return dict;
    }
}

How do I mock getDictionaryFromData to get coverage if error is not nil? Is it possible or do I have to actually mock the JSONObjectWithData method?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Spencer Müller Diniz
  • 1,318
  • 2
  • 14
  • 19
  • 1
    Can you describe what you're trying to test? If you're mocking `getDictionaryFromData:` to test a method that calls it, you could mock it to either return nil or some data. Or you could not mock it and just pass it valid/invalid JSON. It's not clear from your question why the `error` parameter matters. – Christopher Pickslay Mar 12 '14 at 05:51

2 Answers2

3

For this answer I'm assuming you don't actually want to mock the getDictionaryFromData: method. I assume you want to test its implementation, how it deal with an error case.

You can stub that JSONObjectWithData:options:error: method and return an error in the pass by ref argument; somehow like this:

id serializerMock = [OCMock mockForClass:[NSJSONSerialization class]];
NSError *theError = /* create an error */
[[[serializerMock stub] andReturn:nil] JSONObjectWithData:data 
    options:NSJSONReadingAllowFragments error:[OCMArg setTo:theError]];

The trick here is obviously the setTo: method.

Erik Doernenburg
  • 2,933
  • 18
  • 21
0

Here is what worked for me (OCMock 3):

id serializerMock = OCMClassMock(NSJSONSerialization.class);
    NSError *theError = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:NSPropertyListWriteInvalidError userInfo:nil];
    OCMStub(ClassMethod([serializerMock dataWithJSONObject:OCMOCK_ANY
                                                   options:0
                                                     error:[OCMArg setTo:theError]]));

Note: For the line [serializerMock dataWithJSONObject...] Xcode's code completion does not work.

Shanakor
  • 407
  • 1
  • 5
  • 12