我有一个方法我想用OCMock测试,但不知道如何做到这一点。我需要嘲笑
ExtClass
未定义为我的代码(外部库)的一部分:
+(NSString *)foo:(NSString *)param
{
ExtClass *ext = [[ExtClass alloc] initWithParam:param];
if ([ext someMethod])
return @"A";
else
return @"B";
}
提前致谢!
答案 0 :(得分:22)
id mock = [OCMockObject mockForClass:[ExtClass class]];
// We stub someMethod
BOOL returnedValue = YES;
[[[mock stub] andReturnValue:OCMOCK_VALUE(returnedValue)] someMethod];
// Here we stub the alloc class method **
[[[mock stub] andReturn:mock] alloc];
// And we stub initWithParam: passing the param we will pass to the method to test
NSString *param = @"someParam";
[[[mock stub] andReturn:mock] initWithParam:param];
// Here we call the method to test and we would do an assertion of its returned value...
[YourClassToTest foo:param];
// Parameter
NSURL *url = [NSURL URLWithString:@"http://testURL.com"];
// Set up the class to mock `alloc` and `init...`
id mockController = OCMClassMock([WebAuthViewController class]);
OCMStub([mockController alloc]).andReturn(mockController);
OCMStub([mockController initWithAuthenticationToken:OCMOCK_ANY authConfig:OCMOCK_ANY]).andReturn(mockController);
// Expect the method that needs to be called correctly
OCMExpect([mockController handleAuthResponseWithURL:url]);
// Call the method which does the work
[self.myClassInstance authStarted];
OCMVerifyAll(mockController);
确保在两种情况下都存根两个方法(alloc
和init...
方法)。另外,确保两个存根调用都是在类mock的实例上进行的(而不是类本身)。
这个(奇怪的)解决方案可能非常有用,以防您想要测试由于无法重构的原因导致的遗留代码。但是,如果您可以修改代码,则应重构它并将ExtClass
对象作为参数而不是字符串,将ExtClass
的创建委托给该方法。您的生产和测试代码将更简单,更清晰,特别是在更复杂的现实生活中,而不是在这个简单的示例中。