1

I'm trying to understand what is mockable and what isn't.

In an experiment with an NSMutableAttributedString, I don't appear to be able to mock initWithAttributedString.

- (void)test_mutableString_shouldWorkAsAMutableString {
    NSMutableAttributedString *_mutable = [OCMockObject mockForClass:NSMutableAttributedString.class];
    NSAttributedString *_string = [OCMockObject mockForClass:NSAttributedString.class];
    [[[(id)_mutable expect] andReturnValue:nil] initWithAttributedString:_string];
    [_mutable initWithAttributedString:_string];
}

This code won't run; for some reason the proxy for the mutable screen doesn't recognise the initWithAttributedString selector:

2013-03-12 11:25:30.725 UnitTests[11316:c07] TestItClass/test_4_mutableString_shouldWorkAsAMutableString ✘ 0.00s

    Name: NSInvalidArgumentException
    File: Unknown
    Line: Unknown
    Reason: *** -[NSProxy doesNotRecognizeSelector:initWithAttributedString:] called!

    0   CoreFoundation                      0x01c0602e __exceptionPreprocess + 206
    1   libobjc.A.dylib                     0x01948e7e objc_exception_throw + 44
    2   CoreFoundation                      0x01c05deb +[NSException raise:format:] + 139
    3   Foundation                          0x00862bcd -[NSProxy doesNotRecognizeSelector:] + 75
    4   CoreFoundation                      0x01bf5bbc ___forwarding___ + 588
    5   CoreFoundation                      0x01bf594e _CF_forwarding_prep_0 + 14
    6   UnitTests                           0x00349e0b -[TestItClass test_4_mutableString_shouldWorkAsAMutableString] + 283

I am trying to understand how I can reliably use OCMock, but this confuses my and I'm not sure which OCMock calls I can expect to work and which I shouldn't.

I would very much appreciate some clarification on this, and an hints as to why the above doesn't work.

Thanks, Joe

Dr Joe
  • 718
  • 5
  • 19

1 Answers1

2

I learned something about Objective-C trying to figure this one out.

Your basic problem is that the class of an object created by alloc'ing NSMutableAttributedString is not NSMutableAttributedString (always be wary of toll-free bridged classes). To get your code to work, try the following:

NSMutableAttributedString *realMutable = [[NSMutableAttributedString alloc] init];
id mutable = [OCMockObject niceMockForClass:[realMutable class]];
id string = [OCMockObject niceMockForClass:[NSAttributedString class]];

[[[mutable expect] andReturn:@"YO" ] initWithAttributedString:string];
NSLog(@"MOCK: %@", [mutable initWithAttributedString:string]);

[mutable verify];

// Outputs 'MOCK: YO' and passes
Community
  • 1
  • 1
Ben Flynn
  • 18,524
  • 20
  • 97
  • 142
  • Ah, I see. That's a nice way of hiding that wringle and still make the test code maintainable. Thanks! – Dr Joe Apr 25 '13 at 22:05