Use Mockito to mock some methods but not others

To directly answer your question, yes, you can mock some methods without mocking others. This is called a partial mock. See the Mockito documentation on partial mocks for more information. For your example, you can do something like the following, in your test: Stock stock = mock(Stock.class); when(stock.getPrice()).thenReturn(100.00); // Mock implementation when(stock.getQuantity()).thenReturn(200); // Mock implementation … Read more

Using IoC for Unit Testing

Generally speaking, a DI Container should not be necessary for unit testing because unit testing is all about separating responsibilities. Consider a class that uses Constructor Injection public MyClass(IMyDependency dep) { } In your entire application, it may be that there’s a huge dependency graph hidden behind IMyDependency, but in a unit test, you flatten … Read more

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

What is Mocking?

Prologue: If you look up the noun mock in the dictionary you will find that one of the definitions of the word is something made as an imitation. Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want … 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?