-
Option with less dependencies:
<dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.11.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.11.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>5.11.0</version> <scope>test</scope> </dependency>
-
Full option:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.11.0</version>
<scope>test</scope>
</dependency>
- What is Mockito?
- Mockito is an open source testing framework created for Java.
- It allows us to easily create "test doubles" objects in unit tests.
- What is Test Double?
- Test doubles are stand-ins for the real components of your software under test.
- They mimic the behavior of these components, allowing you to test the code in isolation without relying on any dependencies.
- Different testing types require varying functioning features of the software.
- There might be cases where a certain test run may need the function to return a numeric value.
- Choosing the right test double for such test scenarios is critical.
- This is the list of different types of test doubles available:
Types Description Fake Simplified implementation
Basic functionalityStub Predetermined responses
Mimics behaviorMock Behavior verification
Method call trackingDummies Placeholder objects
No functionalitySpies Interaction monitoring
Observes behavior
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>5.14.2</version>
<scope>test</scope>
</dependency>
-
@ExtendWith(MockitoExtension.class)
- To the test class and annotating mocked fields with@Mock
.@RunWith(MockitoJUnitRunner.class)
- JUnit 4
-
@InjectMocks
- Creates an instance of the class and injects the mocks that are created with the@Mock
(or@Spy
) annotations into this instance. -
@Mock
- Creates a mock implementation for the classes we need. -
Example
@ExtendWith(MockitoExtension.class) public class ExampleClassTest { @InjectMocks MyServiceToBeTested myServiceToBeTested; @Mock MyDependency myDependency; }