gpt4 book ai didi

java - doThrow() doAnswer() doNothing() 和 doReturn() 在 mockito 中的用法

转载 作者:IT老高 更新时间:2023-10-28 20:26:43 25 4
gpt4 key购买 nike

我正在学习 mockito,我从 link 中了解了上述函数的基本用法。 .

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

最佳答案

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

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

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

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

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

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:(来自 documentation )使用 doNothing() 将 void 方法设置为不执行任何操作。请注意,模拟上的 void 方法默认情况下什么都不做!但是,doNothing() 派上用场的情况很少见:

  • 对 void 方法的连续调用 stub :

    doNothing().
    doThrow(new RuntimeException())
    .when(mock).someVoidMethod();

    //does nothing the first time:
    mock.someVoidMethod();

    //throws RuntimeException the next time:
    mock.someVoidMethod();
  • 当你窥探真实的对象并且你想让 void 方法什么都不做时:

    List list = new LinkedList();
    List spy = spy(list);

    //let's make clear() do nothing
    doNothing().when(spy).clear();

    spy.add("one");

    //clear() does nothing, so the list still contains "one"
    spy.clear();

关于java - doThrow() doAnswer() doNothing() 和 doReturn() 在 mockito 中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28836778/

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