How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify. Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher’s criteria. They are intended to … Read more

Using Mockito to test abstract classes

The following suggestion let’s you test abstract classes without creating a “real” subclass – the Mock is the subclass. use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract methods that are invoked. Example: public abstract class My { public Result methodUnderTest() { … } protected abstract void methodIDontCareAbout(); } public class MyTest { @Test public void shouldFailOnNullIdentifiers() … Read more

How to mock private method for testing using PowerMock?

I don’t see a problem here. With the following code using the Mockito API, I managed to do just that : public class CodeWithPrivateMethod { public void meaningfulPublicApi() { if (doTheGamble(“Whatever”, 1 << 3)) { throw new RuntimeException(“boom”); } } private boolean doTheGamble(String whatever, int binary) { Random random = new Random(System.nanoTime()); boolean gamble = … Read more

Difference between @Mock and @InjectMocks

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance. Note you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4). With JUnit 5, you must use @ExtendWith(MockitoExtension.class). @RunWith(MockitoJUnitRunner.class) // JUnit 4 // … Read more

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