0

I'm experimenting with using OCMock but so far my simple experiment is failing. Given this experimental class that I want to mock:

@interface HTTPConnection : NSObject  <NSURLConnectionDelegate>
@property (strong, nonatomic)   NSURLConnection  *connection;
-(int) makeConnection:(NSString*) url; // implementation returns 5
@end

When I invoke the following test case, the result variable contains 5 not 15 thus the real object method got invoked and not the mock one:

 - (void)testExample
{
    id connection = [OCMockObject mockForClass:[HTTPConnection class]];
     [[[connection stub] andReturn: [NSNumber numberWithInt: 15]] makeConnection:[OCMArg any]];

    HTTPConnection* realConnection = [[HTTPConnection alloc] init];
    int result = [realConnection makeConnection:@"http://www.anything.com"];
}
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378

1 Answers1

2

First, to stub that method I am not sure if returning a NSNumber works, so I would use the following:

id connection = [OCMockObject mockForClass:[HTTPConnection class]];
int value = 15;
[[[connection stub] andReturnValue:OCMOCK_VALUE(value)] makeConnection:[OCMArg any]];

Second, in your code, when you do [realConnection makeConnection:@"http://www.anything.com"], you are not calling the stubbed method but the real implementation. You should use the your mock object:

int result = [connection makeConnection:@"http://www.anything.com"];

Or, in case you want a partial mock(it seems to me that is what you are looking for):

HTTPConnection* realConnection = [[HTTPConnection alloc] init];
id partialConnection = [OCMockObject partialMockForObject:realConnection];
int value = 15;
[[[partialConnection stub] andReturnValue:OCMOCK_VALUE(value)] makeConnection:[OCMArg any]];

int result = [realConnection makeConnection:@"http://www.anything.com"];
e1985
  • 6,239
  • 1
  • 24
  • 39