問(wèn)題描述
我正在使用 Mockito 進(jìn)行后期單元測(cè)試.我對(duì)何時(shí)使用 doAnswer
和 thenReturn
感到困惑.
I am using Mockito for service later unit testing. I am confused when to use doAnswer
vs thenReturn
.
誰(shuí)能幫我詳細(xì)介紹一下?到目前為止,我已經(jīng)用 thenReturn
進(jìn)行了嘗試.
Can anyone help me in detail? So far, I have tried it with thenReturn
.
推薦答案
當(dāng)你在 mock 一個(gè)方法時(shí)知道返回值時(shí),你應(yīng)該使用 thenReturn
或 doReturn
稱呼.調(diào)用模擬方法時(shí)會(huì)返回此定義的值.
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)
設(shè)置調(diào)用方法時(shí)要返回的返回值.
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
用于在調(diào)用模擬方法時(shí)需要執(zhí)行其他操作,例如當(dāng)需要根據(jù)該方法調(diào)用的參數(shù)計(jì)算返回值時(shí).
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.
當(dāng)您想使用通用 Answer
存根 void 方法時(shí),請(qǐng)使用 doAnswer()
.
Use
doAnswer()
when you want to stub a void method with genericAnswer
.
Answer 指定了一個(gè)執(zhí)行的動(dòng)作和一個(gè)在你與 mock 交互時(shí)返回的返回值.
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");
}
這篇關(guān)于Mockito:doAnswer Vs thenReturn的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!