Home >Java >javaTutorial >How to Selectively Mock Methods in Java with Mockito?
In Java, Mockito allows developers to mock specific methods within a class, while leaving other methods unaffected. This process is known as partial mocking.
Consider the following Stock class:
public class Stock { private final double price; private final int quantity; public Stock(double price, int quantity) { this.price = price; this.quantity = quantity; } public double getPrice() { return price; } public int getQuantity() { return quantity; } public double getValue() { return getPrice() * getQuantity(); } }
In a test scenario, we may want to mock the getPrice() and getQuantity() methods to return specific values. However, we desire the getValue() method to perform its intended calculation.
Using partial mocking, we can achieve this as follows:
Stock stock = mock(Stock.class); when(stock.getPrice()).thenReturn(100.00); when(stock.getQuantity()).thenReturn(200); when(stock.getValue()).thenCallRealMethod();
In this configuration:
Alternatively, we can use the spy() method instead of mock():
Stock stock = spy(Stock.class); doReturn(100.00).when(stock).getPrice(); doReturn(200).when(stock).getQuantity();
In this case, all unstubbed methods (such as getValue()) will invoke their original implementations.
It's worth noting that mocking methods like getPrice() and getQuantity() may not produce the desired result if getValue() relies directly on their values, rather than the mock return values. In such cases, it may be more appropriate to avoid mocking altogether and rely on the actual implementation in the test, as shown below:
Stock stock = new Stock(100.00, 200); double value = stock.getValue(); assertEquals(100.00 * 200, value, 0.00001);
The above is the detailed content of How to Selectively Mock Methods in Java with Mockito?. For more information, please follow other related articles on the PHP Chinese website!