Home > Java > javaTutorial > How to Partially Mock Methods in a Class Using Mockito?

How to Partially Mock Methods in a Class Using Mockito?

DDD
Release: 2024-12-12 15:51:24
Original
388 people have browsed it

How to Partially Mock Methods in a Class Using Mockito?

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template