objective-c - 如何使用未作为参数传递给方法的 OCMock 模拟对象?

标签 objective-c unit-testing ocmock

我想用 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 两个 方法(allocinit... 方法)。此外,确保两个 stub 调用都是在模拟类的实例(而不是类本身)上进行的。

文档:OCMock features 中的类方法部分

备选方案

这个(奇怪的)解决方案在您想测试由于任何原因无法重构的遗留代码时可能很有用。但是,如果您可以修改代码,您应该重构它并获取 ExtClass 对象作为参数,而不是字符串,委托(delegate)该方法创建 ExtClass。您的生产和测试代码会更简单、更清晰,特别是在更复杂的现实案例中,而不是在这个简单的示例中。

关于objective-c - 如何使用未作为参数传递给方法的 OCMock 模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18503604/

相关文章:

ios - 如果用户的iOS版本低于7.0,是否应该使用7.0中不推荐使用的方法?

objective-c - 模拟另一个类方法的内部调用

objective-c - OCMock - 试图模拟 NSEntityDescription

ios - OCMock 在 iOS 中不能正常工作?

scala - 无法加载套件类

python - 写入文件 f 后,调用 f.read() 返回 None

iphone - 使用 Reachability 有什么好处?

ios - 在 sprite kit 中使用渐变效果将 fps 从 60 降低到 30

objective-c - Objective C - iOS,在屏幕外的静态表格单元格内迭代 UILabels

java - 有人可以建议一个带有需求规范文档和 junit 测试的开源 java 项目吗?