問題描述
我正在使用 Mockito 編寫 Java 單元測試,我想驗證某個方法是否是對象上調用的最后一個.
I'm using Mockito to write a unit test in Java, and I'd like to verify that a certain method is the last one called on an object.
我在被測代碼中做了這樣的事情:
I'm doing something like this in the code under test:
row.setSomething(value);
row.setSomethingElse(anotherValue);
row.editABunchMoreStuff();
row.saveToDatabase();
在我的模擬中,我不關心編輯行中所有內容的順序,但重要的是我不在保存后嘗試對其執行更多操作它.有沒有好的方法來做到這一點?
In my mock, I don't care about the order in which I edit everything on the row, but it's very important that I not try to do anything more to it after I've saved it. Is there a good way to do this?
請注意,我不是在尋找 verifyNoMoreInteractions:它不會確認 saveToDatabase 是最后調用的東西,如果我調用行上沒有明確驗證的任何內容,它也會失敗.我希望能夠這樣說:
Note that I'm not looking for verifyNoMoreInteractions: it doesn't confirm that saveToDatabase is the last thing called, and it also fails if I call anything on the row that I don't explicitly verify. I'd like to be able to say something like:
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verifyTheLastThingCalledOn(row).saveToDatabase();
如果有幫助,我將從執行此操作的 JMock 測試切換到 Mockito:
If it helps, I'm switching to Mockito from a JMock test that did this:
row.expects(once()).method("saveToDatabase").id("save");
row.expects(never()).method(ANYTHING).after("save");
推薦答案
我認為這需要更多的自定義工作.
I think it requires more custom work.
verify(row, new LastCall()).saveToDatabase();
然后
public class LastCall implements VerificationMode {
public void verify(VerificationData data) {
List<Invocation> invocations = data.getAllInvocations();
InvocationMatcher matcher = data.getWanted();
Invocation invocation = invocations.get(invocations.size() - 1);
if (!matcher.matches(invocation)) throw new MockitoException("...");
}
}
上一個答案:
你是對的.verifyNoMoreInteractions 是您所需要的.
You are right. verifyNoMoreInteractions is what you need.
verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verify(row).editABunchMoreStuff();
verify(row).saveToDatabase();
verifyNoMoreInteractions(row);
這篇關于使用 Mockito 驗證方法后沒有調用任何內容的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!