問題描述
在我的日常工作中,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 來驗證某個方法從未被調用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!