問題描述
我在學習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 給您答案>在調用該方法時正在執行的接口,此接口允許您通過 InvocationOnMock 參數與參數進行交互.另外,answer 方法的返回值將是 mocked 方法的返回值.
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:(來自 文檔)使用 doNothing() 將 void 方法設置為不執行任何操作.請注意,模擬上的 void 方法默認情況下什么都不做!但是,doNothing() 派上用場的情況很少見:
doNothing: (From documentation) Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing by default! However, there are rare situations when doNothing() comes handy:
對 void 方法的連續調用存根:
Stubbing consecutive calls on a void method:
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod();
//does nothing the first time:
mock.someVoidMethod();
//throws RuntimeException the next time:
mock.someVoidMethod();
當你窺探真實的對象并且你想讓 void 方法什么都不做時:
When you spy real objects and you want the void method to do nothing:
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();
這篇關于doThrow() doAnswer() doNothing() 和 doReturn() 在 mockito 中的用法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!