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

后端 未结 5 1073
庸人自扰
庸人自扰 2020-12-12 16:01

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 othe

相关标签:
5条回答
  • 2020-12-12 16:43

    To add a bit to accepted answer ...

    If you get an UnfinishedStubbingException, be sure to set the method to be stubbed after the when closure, which is different than when you write Mockito.when

    Mockito.doNothing().when(mock).method()    //method is declared after 'when' closes
    
    Mockito.when(mock.method()).thenReturn(something)   //method is declared inside 'when'
    
    0 讨论(0)
  • 2020-12-12 16:47

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

    0 讨论(0)
  • 2020-12-12 16:51

    A very simple example is that if you have a UserService that has @Autowired jpa resposiroty UserRepository

    ...
    class UserService{
    
      @Autowired
      UserRepository userRepository;
    ...
    }
    

    then in the test class for UserService you will do

    ...
    class TestUserService{
      @Mock 
      UserRepository userRepository;
    
      @InjectMocks
      UserService userService;
    
    ...
    }
    

    @InjectMocks tells the framework that take the @Mock UserRepository userRespository; and inject that into userService so rather than auto wiring a real instance of UserRepository a Mock of UserRepository will be injected in userService.

    0 讨论(0)
  • 2020-12-12 16:54

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

    • If you don't use doNothing and you mock an object, the real method is not called
    • If you don't use doNothing and you spy an object, the real method is called

    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.

    0 讨论(0)
  • 2020-12-12 16:55

    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 : 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: 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: 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));
    
    0 讨论(0)
提交回复
热议问题