gpt4 book ai didi

java - 模拟: doAnswer Vs thenReturn

转载 作者:IT老高 更新时间:2023-10-28 11:38:33 27 4
gpt4 key购买 nike

我正在使用 Mockito 进行后期单元测试。我对何时使用 doAnswerthenReturn 感到困惑。

谁能帮我详细介绍一下?到目前为止,我已经用 thenReturn 进行了尝试。

最佳答案

如果在模拟方法调用时知道返回值,则应使用 thenReturndoReturn。调用模拟方法时会返回此定义的值。

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 用于在调用模拟方法时需要执行其他操作,例如当需要根据该方法调用的参数计算返回值时。

Use doAnswer() when you want to stub a void method with generic Answer.

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");
}

关于java - 模拟: doAnswer Vs thenReturn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36615330/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com