在mockito中使用doThrow()doAnswer()doNothing()和doReturn()的用法 [英] Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

查看:3242
本文介绍了在mockito中使用doThrow()doAnswer()doNothing()和doReturn()的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习mockito,我从链接

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

但我想知道它是否可用于其他任何案件?

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

推荐答案

doThrow :当你想在一个方法被调用时抛出一个异常时,基本上使用它一个模拟对象。

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

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

doReturn :当你想要回送一个返回值时使用方法被执行。

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

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

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

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.

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 :这是最简单的清单,基本上它告诉Mockito调用模拟对象中的方法时不执行任何操作。有时用于无效返回方法或没有副作用的方法,或者与您正在进行的单元测试无关。

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.

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

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

这篇关于在mockito中使用doThrow()doAnswer()doNothing()和doReturn()的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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