Use Mockito for Selective Method Mocking
Mockito offers flexibility in mocking specific methods within a class. By leveraging partial mocks, developers can choose which methods to override while leaving others intact.
For example, consider a Stock class with methods getPrice(), getQuantity(), and getValue(). You may desire to mock the first two methods for their return values but let getValue() retain its original behavior.
Using a partial mock in Mockito, you can achieve this precision. The Stock object is instantiated as a mock, while specific expectations are set for getPrice() and getQuantity(). Here's an example:
Stock stock = mock(Stock.class); when(stock.getPrice()).thenReturn(100.00); when(stock.getQuantity()).thenReturn(200);
By calling thenCallRealMethod() for getValue(), you preserve its actual implementation:
when(stock.getValue()).thenCallRealMethod();
Alternatively, a spy can be utilized, where all methods initially reference the real implementation. Only those methods explicitly stubbed will adopt the altered behavior. Here's the spy approach:
Stock stock = spy(Stock.class); when(stock.getPrice()).thenReturn(100.00); when(stock.getQuantity()).thenReturn(200);
Note that when using spies, it's crucial to avoid calling the real method within a stubbed method.
Yet another option involves the Mockito.CALLS_REAL_METHODS flag:
Stock MOCK_STOCK = Mockito.mock( Stock.class, CALLS_REAL_METHODS );
This approach delegates unstubbed methods to their actual implementations.
However, in the given Stock example, this partial mocking strategy may still fail due to the dependency of getValue() on both price and quantity directly, not solely on their getters.
Additionally, consider outright avoidance of mocks when possible:
Stock stock = new Stock(100.00, 200); double value = stock.getValue(); assertEquals("Stock value not correct", 100.00*200, value, .00001);
The above is the detailed content of How Can I Selectively Mock Methods in Mockito for Partial Mocking?. For more information, please follow other related articles on the PHP Chinese website!