問題描述
我有一個相當復雜的 java 函數,我想使用 jUnit 進行測試,為此我正在使用 Mockito.這個函數看起來像這樣:
I have a rather complex java function that I want to test using jUnit and I am using Mockito for this purpose. This function looks something like this:
public void myFunction (Object parameter){
...
doStuff();
...
convert(input,output);
...
parameter.setInformationFrom(output);
}
convert 函數根據輸入設置輸出的屬性,它是一個 void 類型的函數,盡管輸出"是參數是正在使用的,就好像它是由函數返回的一樣.這個轉換函數是我想要模擬的,因為我不需要依賴于測試的輸入,但我不知道該怎么做,因為我對 Mockito 不是很熟悉.
The function convert sets the attributes of output depending on input and it's a void type function, although the "output" parameter is what is being used as if it were returned by the function. This convert function is what I want to mock up as I don't need to depend on the input for the test, but I don't know how to do this, as I am not very familiar with Mockito.
我見過的基本情況是 when(something).thenReturn(somethingElse)
或我理解的 doAnswer
方法與前一個方法類似,但可以添加更多邏輯,但我認為這些情況不適合我的情況,因為我的函數沒有返回語句.
I have seen basic cases as when(something).thenReturn(somethingElse)
or the doAnswer
method which I understand is similar to the previous one but more logic can be added to it, but I don't think these cases are appropriate for my case, as my function does not have a return statement.
推薦答案
如果您希望模擬方法在(或以其他方式更改)參數上調用方法,您需要像這個問題一樣寫一個答案(如何模擬影響對象的 void 返回方法").
If you want the mocked method to call a method on (or otherwise alter) a parameter, you'll need to write an Answer as in this question ("How to mock a void return method affecting an object").
來自 Kevin Welker 的 回答那里:
doAnswer(new Answer() {
Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
return null; // void method, so return null
}
}).when(mock).someMethod();
請注意,較新的最佳實踐將具有 Answer 的類型參數,如 Answer
,并且 Java 8 的 lambda 可以進一步壓縮語法.例如:
Note that newer best-practices would have a type parameter for Answer, as in Answer<Void>
, and that Java 8's lambdas can compress the syntax further. For example:
doAnswer(invocation -> {
Object[] args = invocation.getArguments();
((MyClass)args[0]).myClassSetMyField(NEW_VALUE);
return null; // void method in a block-style lambda, so return null
}).when(mock).someMethod();
這篇關于修改 void 函數的輸入參數,然后讀取的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!