0

I'm mocking a protocol using OCMock. I tried setting my properties for my mockDelegate, but it doesn't get set. Am I doing something wrong?

id mockDelegate = [OCMockObject mockForProtocol:@protocol(TestDelegate)];
[mockDelegate setMyFloatProperty:100.0];
iamarnold
  • 705
  • 1
  • 8
  • 22

1 Answers1

0

OCMock will create methods for you that implement the protocol (including the myFloatValue property), however, by default, they don't do anything beyond the default for a nil object:

- (CGFloat)myFloatProperty {
    return 0.0f;
}

- (void)setMyFloatProperty {
}

If you want myFloatProperty to always return a specific value, you need to stub that property's getter using OCMStub:

id mock = OCMProtocolMock(@protocol(TestDelegate));
[mock setMyFloatProperty:100.0f];
NSLog(@"%f", [mock myFloatProperty]);  // prints 0.000000
OCMStub([mock myFloatProperty]).andReturn(100.0f);
NSLog(@"%f", [mock myFloatProperty]);  // prints 100.000000

If you want the property to be able to be changed during the course of your test, there are a few options. The easiest way is to create a stub property on your test case class, and redirect the stub methods to that property.

@interface MyTestCase : XCTestCase
@property CGFloat stubMyFloatProperty;
@end

@implementation MyTestCase

- (void)testTestDelegate {

    id mock = OCMProtocolMock(@protocol(TestDelegate));
    [[[[mock stub] ignoringNonObjectArgs] andCall:@selector(setStubMyFloatProperty:) onObject:self] setMyFloatProperty:0.0f];
    OCMStub([mock myFloatProperty]).andCall(self, @selector(stubMyFloatProperty));

    [mock setMyFloatProperty:100.0f];
    NSLog(@"%f", [mock myFloatProperty]);  // prints 100.000000

}    

@end

Note that, because myFloatProperty is a primitive type, you have to use non-standard OCMock syntax in order to stub it properly for arbitrary values. See this answer for further details.

Community
  • 1
  • 1
Chris Vig
  • 8,552
  • 2
  • 27
  • 35
  • How do I stub a CLLocation? I tried the same method for float, but plugged in a CLLocation instead and I get a null. – iamarnold Mar 29 '16 at 15:43