問題描述
我正在使用 Mockito 進行后期單元測試.我對何時使用 doAnswer
和 thenReturn
感到困惑.
I am using Mockito for service later unit testing. I am confused when to use doAnswer
vs thenReturn
.
誰能幫我詳細介紹一下?到目前為止,我已經用 thenReturn
進行了嘗試.
Can anyone help me in detail? So far, I have tried it with thenReturn
.
推薦答案
當你在 mock 一個方法時知道返回值時,你應該使用 thenReturn
或 doReturn
稱呼.調用模擬方法時會返回此定義的值.
You should use thenReturn
or doReturn
when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.
thenReturn(T value)
設置調用方法時要返回的返回值.
thenReturn(T value)
Sets a return value to be returned when the method is called.
@Test
public void test_return() throws Exception {
Dummy dummy = mock(Dummy.class);
int returnValue = 5;
// choose your preferred way
when(dummy.stringLength("dummy")).thenReturn(returnValue);
doReturn(returnValue).when(dummy).stringLength("dummy");
}
Answer
用于在調用模擬方法時需要執行其他操作,例如當需要根據該方法調用的參數計算返回值時.
Answer
is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.
當您想使用通用 Answer
存根 void 方法時,請使用 doAnswer()
.
Use
doAnswer()
when you want to stub a void method with genericAnswer
.
Answer 指定了一個執行的動作和一個在你與 mock 交互時返回的返回值.
Answer specifies an action that is executed and a return value that is returned when you interact with the mock.
@Test
public void test_answer() throws Exception {
Dummy dummy = mock(Dummy.class);
Answer<Integer> answer = new Answer<Integer>() {
public Integer answer(InvocationOnMock invocation) throws Throwable {
String string = invocation.getArgumentAt(0, String.class);
return string.length() * 2;
}
};
// choose your preferred way
when(dummy.stringLength("dummy")).thenAnswer(answer);
doAnswer(answer).when(dummy).stringLength("dummy");
}
這篇關于Mockito:doAnswer Vs thenReturn的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!