Mockito:doAnswer Vs thenReturn

Mockito : doAnswer Vs thenReturn(Mockito:doAnswer Vs thenReturn)
本文介绍了Mockito:doAnswer Vs thenReturn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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 一个方法时知道返回值时,你应该使用 thenReturndoReturn称呼.调用模拟方法时会返回此定义的值.

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 generic Answer.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)