Java mockito 中 doThrow() doAnswer() doNothing() 和 doReturn() 的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28836778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:55:16  来源:igfitidea点击:

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

javamockito

提问by User666

I was learning mockito and I understood the basic usages of the above mentioned functions from the link.

我正在学习mockito,并从链接中了解了上述功能的基本用法。

But I would like to know whether it can be used for any other cases?

但是我想知道它是否可以用于任何其他情况?

回答by Koitoer

doThrow: Basically used when you want to throw an exception when a method is being called within a mock object.

doThrow:主要用于在模拟对象中调用方法时要抛出异常。

public void validateEntity(final Object object){}
Mockito.doThrow(IllegalArgumentException.class)
.when(validationService).validateEntity(Matchers.any(AnyObjectClass.class));

doReturn: Used when you want to send back a return value when a method is executed.

doReturn:当您想在执行方法时发回返回值时使用。

public Socket getCosmosSocket() throws IOException {}
Mockito.doReturn(cosmosSocket).when(cosmosServiceImpl).getCosmosSocket();

doAnswer: Sometimes you need to do some actions with the arguments that are passed to the method, for example, add some values, make some calculations or even modify them doAnswer gives you the Answer interface that being executed in the moment that method is called, this interface allows you to interact with the parameters via the InvocationOnMock argument. Also, the return value of answer method will be the return value of the mocked method.

doAnswer:有时您需要对传递给方法的参数执行一些操作,例如,添加一些值,进行一些计算甚至修改它们 doAnswer 为您提供在调用该方法时正在执行的 Answer 接口,此接口允许您通过 InvocationOnMock 参数与参数进行交互。此外, answer 方法的返回值将是模拟方法的返回值。

public ReturnValueObject quickChange(Object1 object);
Mockito.doAnswer(new Answer<ReturnValueObject>() {

        @Override
        public ReturnValueObject answer(final InvocationOnMock invocation) throws Throwable {

            final Object1 originalArgument = (invocation.getArguments())[0];
            final ReturnValueObject returnedValue = new ReturnValueObject();
            returnedValue.setCost(new Cost());

            return returnedValue ;
        }
}).when(priceChangeRequestService).quickCharge(Matchers.any(Object1.class));

doNothing: Is the easiest of the list, basically it tells Mockito to do nothing when a method in a mock object is called. Sometimes used in void return methods or method that does not have side effects, or are not related to the unit testing you are doing.

doNothing:是列表中最简单的,基本上它告诉 Mockito 在调用模拟对象中的方法时什么都不做。有时用于 void 返回方法或没有副作用的方法,或者与您正在执行的单元测试无关。

public void updateRequestActionAndApproval(final List<Object1> cmItems);

Mockito.doNothing().when(pagLogService).updateRequestActionAndApproval(
                Matchers.any(Object1.class));

回答by Rodrigo Asensio

If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.

如果您正在测试一个逻辑类并且它正在调用一些内部 void 方法,那么 doNothing 是完美的。

回答by David Obber

It depends on the kind of test double you want to interact with:

这取决于您要与之交互的测试替身类型:

  • If you don't use doNothing and you mockan object, the real method is not called
  • If you don't use doNothing and you spyan object, the real method is called
  • 如果不使用 doNothing 并模拟对象,则不会调用真正的方法
  • 如果你不使用 doNothing 并监视一个对象,则调用真正的方法

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

换句话说,通过模拟,与合作者唯一有用的交互是您提供的交互。默认情况下,函数将返回 null,void 方法什么也不做。

回答by Toseef Zafar

A very simple example is that if you have a UserServicethat has @Autowiredjpa resposiroty UserRepository

一个非常简单的例子是,如果你有一个UserService具有@Autowiredjpa resposirotyUserRepository

...
class UserService{

  @Autowired
  UserRepository userRepository;
...
}

then in the test class for UserServiceyou will do

然后在测试课中为UserService你做

...
class TestUserService{
  @Mock 
  UserRepository userRepository;

  @InjectMocks
  UserService userService;

...
}

@InjectMockstells the framework that take the @Mock UserRepository userRespository;and inject that into userServiceso rather than auto wiring a real instance of UserRepositorya Mock of UserRepositorywill be injected in userService.

@InjectMocks告诉框架接受@Mock UserRepository userRespository;并将其注入userServiceso 而不是自动连接将注入UserRepository的 Mock 的真实实例。UserRepositoryuserService