Mockito:doAnswer Vs然后返回 [英] Mockito : doAnswer Vs thenReturn

查看:253
本文介绍了Mockito:doAnswer Vs然后返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito进行后期单元测试。我很困惑何时使用 doAnswer vs 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.

推荐答案

您应该使用 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 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.


使用 doAnswer()当你想使用泛型答案来存根一个void方法时。

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

这篇关于Mockito:doAnswer Vs然后返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆