How to Mock Specific Methods in a Class Using Mockito
In software testing, mocking allows you to simulate the behavior of a dependency or a class you don't want to instantiate directly. Mockito is a Java mocking framework that enables you to mock methods and verify interactions with them.
Specifically, you may encounter scenarios where you want to mock certain methods of a class while leaving others untouched. This approach is known as partial mocking. Here's how you can achieve it using Mockito:
// Mock the Stock class with partial mocking Stock stock = mock(Stock.class); // Mock specific methods when(stock.getPrice()).thenReturn(100.00); when(stock.getQuantity()).thenReturn(200); // Leave 'getValue()' unmocked // It will execute the actual Stock.getValue() calculation when(stock.getValue()).thenCallRealMethod();
This way, only the getPrice() and getQuantity() methods will be mocked, while getValue() will execute its original code.
Additionally, you can use the CALLS_REAL_METHODS argument with Mockito.mock():
Stock MOCK_STOCK = Mockito.mock(Stock.class, CALLS_REAL_METHODS);
This will delegate unstubbed calls to real implementations.
However, it's important to note that in your example, mocking only getPrice() and getQuantity() won't work correctly because the getValue() implementation depends on their actual return values. Instead, consider avoiding mocks altogether:
// Without mocks Stock stock = new Stock(100.00, 200); double value = stock.getValue();
The above is the detailed content of How to Partially Mock Methods in a Class Using Mockito?. For more information, please follow other related articles on the PHP Chinese website!