如何使用 OCMock 验证某个方法从未被调用?
在我的日常工作中,我被 Mockito的never()
验证,可以确认mock方法从未被调用。
有没有办法使用 Objective-C 和 OCMock 完成同样的事情?我一直在使用下面的代码,它可以工作,但感觉就像是黑客攻击。我希望有更好的方法...
- (void)testSomeMethodIsNeverCalled {
id mock = [OCMockObject mockForClass:[MyObject class]];
[[[mock stub] andCall:@selector(fail) onObject:self] forbiddenMethod];
// more test things here, which hopefully
// never call [mock forbiddenMethod]...
}
- (void)fail {
STFail(@"This method is forbidden!");
}
At my day job I've been spoiled with Mockito's never()
verification, which can confirm that a mock method is never called.
Is there some way to accomplish the same thing using Objective-C and OCMock? I've been using the code below, which works but it feels like a hack. I'm hoping there's a better way...
- (void)testSomeMethodIsNeverCalled {
id mock = [OCMockObject mockForClass:[MyObject class]];
[[[mock stub] andCall:@selector(fail) onObject:self] forbiddenMethod];
// more test things here, which hopefully
// never call [mock forbiddenMethod]...
}
- (void)fail {
STFail(@"This method is forbidden!");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从 OCMock 的 r69 开始,可以拒绝方法调用 http://svn.mulle-kybernetik。 com/OCMock/trunk/Source/Changes.txt
引用自:http://www.mulle-kybernetik.com/software/OCMock/#features
Since r69 of OCMock, it's possible to reject a method call http://svn.mulle-kybernetik.com/OCMock/trunk/Source/Changes.txt
Quoted from: http://www.mulle-kybernetik.com/software/OCMock/#features
据我所知,当你调用 verify 并调用未记录的方法时,OCMock 会自动失败。如果调用了意外的方法,则不会抱怨的模拟称为“好的模拟”。
As far as I know OCMock will fail automatically when you call verify and methods that have not been recorded were called. A mock that wouldn't complain if unexpected methods were called is called a "nice mock".
从版本 3.3 开始,OCMock 有 OCMReject 宏。
Starting from version 3.3 OCMock has OCMReject macro.
您可能还发现有必要确保永远不会在您部分模拟的对象上调用方法。
我为此创建了一个宏:
我这样使用它:
You may also find it necessary to ensure a method is never being called on an object you are partially mocking.
I created a macro for this:
I use it like this:
您也可以尝试类似的方法,如 JavaScript:
我不确定是否存在与此代码相关的任何泄漏。我通过阅读此页面得到了这个想法: http://thirdcog.eu/pwcblocks/
You could also try something like this, a la JavaScript:
I'm not sure if there are any leaks associated with this code. I got the idea from reading this page: http://thirdcog.eu/pwcblocks/
为了确保你的方法没有被调用,我认为我们必须在调用
testMethod
之前进行断言。因此,请确保在运行测试方法之前放置OCMReject
,以侦听运行testMethod
时将触发哪个方法:To make sure your method not called, I think we have to do an assert before the
testMethod
called. So make sure putOCMReject
before you run the test method to listen which method will trigger when runstestMethod
: