Home > Java > javaTutorial > How Can I Selectively Mock Methods in Mockito for Partial Mocking?

How Can I Selectively Mock Methods in Mockito for Partial Mocking?

Patricia Arquette
Release: 2024-12-20 20:11:10
Original
915 people have browsed it

How Can I Selectively Mock Methods in Mockito for Partial Mocking?

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);
Copy after login

By calling thenCallRealMethod() for getValue(), you preserve its actual implementation:

when(stock.getValue()).thenCallRealMethod();
Copy after login

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);
Copy after login

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 );
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template