Java Programmers: Discover How to Mock Spring in 4 Steps!
Writing tests is not easy even when you're mixing some framework.
Because of this, this article will help you to decide which kind of mock to use for each coverage type.
In the picture below, we can see the model, a simple model, but enough to understand the mocks.
1. Mock
Use org.mockito.Mock
when unit testing your business logic (only using JUnit and Mockito).
1.1. Scope
1.2. Code
1.3. Benefits
Isolate the scope of the test, ie, we're not starting the application to test the method, the scope is just called the method and verify
1.4. Drawbacks
Calling the service creates an instance manually :(
2. InjectMocks
The use of org.mockito.InjectMocks
, enable us to mock any call for the subject, ie, looking at line 39, any call to the CustomerDAO.findAllCustomers
will return a list with one element.
2.1. Scope
The test scope is marked as the black rectangle on the diagram below
2.2. Code
2.3. Benefits
You're testing a component that's great! Besides you can initialize the component (Bean) using the annotation ExtendsWith
or using the MockitoAnnotations.openMocks(this)
2.4. Drawbacks
Since this is a UT, I cannot see any drawbacks.
3. MockBean
Use @org.springframework.boot.test.mock.mockito.MockBean
when you write a test that is backed by a Spring Test Context and you want to add or replace a bean with a mocked version of it.
3.1. Scope
3.2. Code
3.3. Benefits
This kind of test using SpringBootTest
enables us to run the Spring Boot application, but pay attention to external resources, ie, Database, Queue, and External Services. Those services should be mocked and properly configured.
Since is out of the scope of this article, those resources will not be covered.
3.4. Drawbacks
Additional work to make your whole application works, if you have resources.
4. No Mocks
This is a bonus section.
Since this is a small application without any Controller or Resource, is a piece of cake to avoid mocks, but this is not the rule is the exception.
4.1. Scope
4.2. Code
4.3. Benefits
This kind of test could be classified as E2E (End To End) test since there are no resources.
4.4. Drawback
If you don't have any resources I can't see any drawback.
If you like the content, please give claps 👏 and follow me for more
5. Stack
- Java 11
- Spring Boot 2.7.11
- Gradle
- JUnit 5
- Gradle 7.4
- IntelliJ Ultimate