我想用 OCMock 测试一种方法,但不确定如何进行。我需要 mock
ExtClass
未定义为我的代码(外部库)的一部分:
+(NSString *)foo:(NSString *)param
{
ExtClass *ext = [[ExtClass alloc] initWithParam:param];
if ([ext someMethod])
return @"A";
else
return @"B";
}
提前致谢!
最佳答案
OCMock 2
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];
OCMock3
// 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);
注意事项
确保在这两种情况下,您 stub 两个 方法(alloc
和init...
方法)。此外,确保两个 stub 调用都是在模拟类的实例(而不是类本身)上进行的。
文档:OCMock features 中的类方法部分
备选方案
这个(奇怪的)解决方案在您想测试由于任何原因无法重构的遗留代码时可能很有用。但是,如果您可以修改代码,您应该重构它并获取 ExtClass
对象作为参数,而不是字符串,委托(delegate)该方法创建 ExtClass
。您的生产和测试代码会更简单、更清晰,特别是在更复杂的现实案例中,而不是在这个简单的示例中。
关于objective-c - 如何使用未作为参数传递给方法的 OCMock 模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18503604/