How to mock void methods with Mockito

前端 未结 9 2109
情话喂你
情话喂你 2020-11-22 12:21

How to mock methods with void return type?

I implemented an observer pattern but I can\'t mock it with Mockito because I don\'t know how.

And I tried to fin

9条回答
  •  隐瞒了意图╮
    2020-11-22 12:59

    How to mock void methods with mockito - there are two options:

    1. doAnswer - If we want our mocked void method to do something (mock the behavior despite being void).
    2. doThrow - Then there is Mockito.doThrow() if you want to throw an exception from the mocked void method.

    Following is an example of how to use it (not an ideal usecase but just wanted to illustrate the basic usage).

    @Test
    public void testUpdate() {
    
        doAnswer(new Answer() {
    
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                if (arguments != null && arguments.length > 1 && arguments[0] != null && arguments[1] != null) {
    
                    Customer customer = (Customer) arguments[0];
                    String email = (String) arguments[1];
                    customer.setEmail(email);
    
                }
                return null;
            }
        }).when(daoMock).updateEmail(any(Customer.class), any(String.class));
    
        // calling the method under test
        Customer customer = service.changeEmail("old@test.com", "new@test.com");
    
        //some asserts
        assertThat(customer, is(notNullValue()));
        assertThat(customer.getEmail(), is(equalTo("new@test.com")));
    
    }
    
    @Test(expected = RuntimeException.class)
    public void testUpdate_throwsException() {
    
        doThrow(RuntimeException.class).when(daoMock).updateEmail(any(Customer.class), any(String.class));
    
        // calling the method under test
        Customer customer = service.changeEmail("old@test.com", "new@test.com");
    
    }
    }
    

    You could find more details on how to mock and test void methods with Mockito in my post How to mock with Mockito (A comprehensive guide with examples)

提交回复
热议问题