我该如何在OCMockito中添加类方法? [英] How do I stub a class method with OCMockito?
问题描述
OCMockito文档声称可以模拟类对象,但是我无法确定如何解决.以下测试失败,并显示Expected "Purple" but was ""
:
The OCMockito documentation claims it's possible to mock class objects, but I'm damned if I can work out how. The following test fails with Expected "Purple" but was ""
:
- (void)testClassMethodMocking
{
Class stringClassMock = mockClass([NSString class]);
[given([stringClassMock string]) willReturn:@"Purple"];
assertThat([NSString string], equalTo(@"Purple"));
}
如果以上链接的常见问题解答如何模拟类对象?"的答案 not 暗示是否有可能将类方法的返回值存根,它用于什么 ?
If the answer to the abovelinked FAQ section "How do you mock a class object?" does not imply it's possible stub the return value of a class method, what is it used for?
当然,以上只是一个退化的示例,实际的[NSString string]调用位于被测方法内部:
Of course the above is a degenerate example, the real [NSString string] call is inside the method under test:
- (NSString *)methodThatCallsAClassMethod
{
return [NSString string];
}
...使上面的断言看起来像:
... making the assert above look like:
assertThat([testedObject methodThatCallsAClassMethod], equalTo(@"Purple"));
因此,上述完全无效的方法行不通吗?那么,我如何实现我想在这里做的事情?
So the above just flat-out won't work? How do I achieve what I want to do here, then?
推荐答案
您的断言语句直接使用NSString.改用模拟:
Your assertion statement is using NSString directly. Use the mock instead:
assertThat([stringClassMock string], equalTo(@"Purple"));
换句话说,该模拟不会使实际的NSString混乱.而是它的替身.
In other words, the mock isn't swizzling the actual NSString. Rather, it's a stand-in for it.
在您编辑的示例中,您的"methodThatCallsAClassMethod"对NSString具有依赖性.如果要替换它,则需要注入类或Subclass and Override Method.
In your edited example, your "methodThatCallsAClassMethod" has a dependency on NSString. If you wanted to replace that, you either need to inject the class, or Subclass and Override Method.
注射:
return [self.stringClass string];
然后,您可以将stringClass
属性设置为模拟对象.
Then you can set the stringClass
property to a mock.
子类和覆盖方法:
@interface TestingFoo : Foo
@end
@implementation @TestingFoo
- (NSString *)methodThatCallsAClassMethod
{
// return whatever you want
}
@end
这篇关于我该如何在OCMockito中添加类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!