How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods. For example, Mockito.doThrow(new Exception()).when(instance).methodName(); or if you want to combine it with follow-up behavior, Mockito.doThrow(new Exception()).doNothing().when(instance).methodName(); Presuming that you are looking at … Read more

How to mock a final class with mockito

Mockito 2 now supports final classes and methods! But for now that’s an “incubating” feature. It requires some steps to activate it which are described in What’s New in Mockito 2: Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to … Read more

Mocking static methods with Mockito

Use PowerMockito on top of Mockito. Example code: @RunWith(PowerMockRunner.class) @PrepareForTest(DriverManager.class) public class Mocker { @Test public void shouldVerifyParameters() throws Exception { //given PowerMockito.mockStatic(DriverManager.class); BDDMockito.given(DriverManager.getConnection(…)).willReturn(…); //when sut.execute(); // System Under Test (sut) //then PowerMockito.verifyStatic(); DriverManager.getConnection(…); } More information: Why doesn’t Mockito mock static methods?