非常简单的基本OCMock存根不工作

时间:2013-05-08 19:01:05

标签: ios ocmock

我正在尝试使用OCMock,但到目前为止,我的简单实验失败了。鉴于我想要模拟的实验课:

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

当我调用以下测试用例时,结果变量包含5而不是15,因此调用了真实对象方法而不是模拟对象:

 - (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"];
}

1 个答案:

答案 0 :(得分:2)

首先,对于该方法的存根,我不确定返回NSNumber是否有效,所以我将使用以下内容:

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

其次,在您的代码中,当您执行[realConnection makeConnection:@"http://www.anything.com"]时,您不会调用存根方法,而是实际实现。你应该使用你的模拟对象:

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

或者,如果你想要部分模拟(在我看来这就是你要找的):

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"];