問題描述
在我的日常工作中,Mockito的never()
驗(yàn)證,可以確認(rèn)一個(gè)mock方法永遠(yuǎn)不會(huì)被調(diào)用.
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 來完成同樣的事情?我一直在使用下面的代碼,它可以工作,但感覺就像一個(gè)黑客.我希望有更好的方法...
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開始,可以拒絕一個(gè)方法調(diào)用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
很好的模擬/快速失敗當(dāng)一個(gè)方法在模擬對(duì)象上調(diào)用尚未設(shè)置任何期望或存根模擬對(duì)象將引發(fā)例外.這種故障快速模式可以通過創(chuàng)建一個(gè)不錯(cuò)的"模擬來關(guān)閉:
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]]
雖然漂亮的模擬會(huì)簡單地忽略所有意想不到的方法都是可能的禁止特定方法:
While nice mocks will simply ignore all unexpected methods it is possible to disallow specific methods:
[[mock reject] someMethod]
請(qǐng)注意,在故障快速模式下,如果異常被忽略,它將是調(diào)用驗(yàn)證時(shí)重新拋出.這可以確保來自的不需要的調(diào)用可以檢測到通知等.
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
這篇關(guān)于如何使用 OCMock 來驗(yàn)證某個(gè)方法從未被調(diào)用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!