目标C& OC Mock - 模拟类方法?
我需要能够确定是否调用了类方法。 我怎样才能用 OCMock 做到这一点?
I need to be able to determine whether a class method was called or not.
How can I do this with OCMock?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 OCMock 版本 2.1 开始,这是开箱即用的支持。现在,您可以使用与存根实例方法相同的方式存根类方法。
Starting with OCMock release 2.1 this is supported out of the box. You can now stub class methods in the same way as you stub instance methods.
一种方法是将类方法包装在您自己的类的方法中。假设您的类必须调用
[SomeOtherClass classMethod:someString]
。您可以在您的类上创建一个方法invokeClassMethod:
,如下所示:然后在您的测试中,您创建一个部分模拟并期望
invokeClassMethod:
如果您想验证
invokeClassMethod
没有被调用,你可以抛出异常:如果调用
invokeClassMethod
,异常将导致测试失败。One approach is to wrap the class method in a method on your own class. So let's say your class has to call
[SomeOtherClass classMethod:someString]
. You could create a methodinvokeClassMethod:
on your class like this:Then in your test, you create a partial mock and expect
invokeClassMethod:
If you want to verify that
invokeClassMethod
isn't called, you can throw an exception:The excpetion will cause the test to fail if
invokeClassMethod
is called.正如 zneak 在对您的问题的评论中提到的,请查看 这个答案,
从那里的评论中,查看类方法的这个基于块的实现搅动。
OCMock
似乎并不直接支持你想要做的事情,但是这个解决方案非常好!As zneak mentioned in their comment to your question, have a look at this answer,
And from the comments there, checkout this block-based implementation of class method swizzling.
OCMock
doesnt seem to directly support what you want to do, but this solution is quite nice!或者,假设您有类:
并且您想要模拟此类方法。一种选择是在此类上创建一个类别,用于定义和实现测试支持。然后,您可以将被测类中的类方法的实现与类别中的模拟方法交换。
Alternatively, lets assume that you have the class:
and you want to mock this class method. One option is to create a category on this class which defines and implements testing support. Then, you can swap the implementation of the class method in the class under test with your mock one from the category.