如何使用 OCMock 来验证某个方法从未被调用?

How can I use OCMock to verify that a method is never called?(如何使用 OCMock 来验证某个方法从未被调用?)
本文介绍了如何使用 OCMock 来验证某个方法从未被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在我的日常工作中,Mockito的never()验证,可以确认一个mock方法永远不会被调用.

At my day job I've been spoiled with Mockito's never() verification, which can confirm that a mock method is never called.

有没有什么方法可以使用 Objective-C 和 OCMock 来完成同样的事情?我一直在使用下面的代码,它可以工作,但感觉就像一个黑客.我希望有更好的方法...

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!");
}

推荐答案

从OCMock r69开始,可以拒绝一个方法调用http://svn.mulle-kybernetik.com/OCMock/trunk/Source/Changes.txt

Since r69 of OCMock, it's possible to reject a method call http://svn.mulle-kybernetik.com/OCMock/trunk/Source/Changes.txt

很好的模拟/快速失败当一个方法在模拟对象上调用尚未设置任何期望或存根模拟对象将引发例外.这种故障快速模式可以通过创建一个不错的"模拟来关闭:

Nice mocks / failing fast When a method is called on a mock object that has not been set up with either expect or stub the mock object will raise an exception. This fail-fast mode can be turned off by creating a "nice" mock:

id mock = [OCMockObject niceMockForClass:[SomeClass class]]

虽然漂亮的模拟会简单地忽略所有意想不到的方法都是可能的禁止特定方法:

While nice mocks will simply ignore all unexpected methods it is possible to disallow specific methods:

[[mock reject] someMethod]

请注意,在故障快速模式下,如果异常被忽略,它将是调用验证时重新抛出.这可以确保来自的不需要的调用可以检测到通知等.

Note that in fail-fast mode, if the exception is ignored, it will be rethrown when verify is called. This makes it possible to ensure that unwanted invocations from notifications etc. can be detected.

引自:http://www.mulle-kybernetik.com/software/OCMock/#features

这篇关于如何使用 OCMock 来验证某个方法从未被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Mockito - what does verify method do?(Mockito - 验证方法有什么作用?)
Is there a native YAML library for iPhone?(是否有适用于 iPhone 的本机 YAML 库?)
UITextField - UIKeyboardTypeDecimalPad on iPad?(UITextField - iPad 上的 UIKeyboardTypeDecimalPad?)
How to draw stars using Quartz Core?(如何使用 Quartz Core 绘制星星?)
Why does giving addArcWithCenter a startAngle of 0 degrees make it start at 90 degrees?(为什么给 addArcWithCenter 一个 0 度的 startAngle 使它从 90 度开始?)
Are ints always initialized to 0?(整数总是初始化为0吗?)