0% found this document useful (0 votes)
17 views8 pages

Mockito

Mockito is a Java framework designed for mocking objects in unit tests, enabling developers to test classes in isolation by simulating interactions with dependencies. It focuses on behavior-driven development, allowing for faster and more accurate tests by avoiding real implementations and facilitating error simulation. Key components include mocks, stubbing, and verification, with specific annotations like @Mock, @InjectMocks, and @MockBean used for effective testing in Spring Boot applications.

Uploaded by

navneetgupta2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views8 pages

Mockito

Mockito is a Java framework designed for mocking objects in unit tests, enabling developers to test classes in isolation by simulating interactions with dependencies. It focuses on behavior-driven development, allowing for faster and more accurate tests by avoiding real implementations and facilitating error simulation. Key components include mocks, stubbing, and verification, with specific annotations like @Mock, @InjectMocks, and @MockBean used for effective testing in Spring Boot applications.

Uploaded by

navneetgupta2022
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Mockito

What is Mockito?
 Mockito is a Java framework used to mock objects in unit tests.
 It allows you to simulate dependencies (like services or repositories)
and focus only on the class being tested.
 Goal: Test classes in isolation by simulating interactions with other
components.
 Mockito focuses on behavior-driven development (BDD) by verifying
interactions between objects rather than their internal state.
Architecture Overview
Mockito's architecture revolves around three key components:
Compon Description
ent
Mock A fake object that mimics the behavior of real objects.
Created using mock().
Stubbin Defining what the mock should do when certain
g methods are called (e.g., when().thenReturn()).
Verificat Ensuring that certain methods on the mock were
ion called, and how many times (verify()).
How Mockito Works (Flow)
 Create Mocks – Fake objects for classes or interfaces using
mock().
 Stub Behavior – Define how the mock should behave using
when().thenReturn().
 Call Methods – Execute methods on the class under test that
interact with the mocked object.
 Verify Interactions – Check if the methods were called and if
they behaved as expected.

Why Use Mockito?


 Decouples tests from real implementations.
 Faster tests by avoiding actual database/API calls.
 Simulates errors or specific scenarios (like null or
exceptions).

Setup – Adding Mockito to Spring Boot Project

Add the following to your pom.xml for Maven:

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.0.0</version>
<scope>test</scope>
</dependency>

Basic Concepts:
 Mocking – Create fake objects.
 Stubbing – Define behavior for mock methods.
 Verification – Ensure certain methods were called.

How Mockito Avoids Complex Setups


 Without Mockito: You need real objects (like databases or
APIs) for testing.
 With Mockito: Fake objects replace dependencies, isolating
the class being tested.

Mockito's Benefits
 Isolation: Tests are not dependent on other services or
databases.
 Speed: Mocks avoid heavy operations, speeding up test
execution.
 Flexibility: Simulates various conditions (like exceptions or
null responses).
 Accuracy: Focuses solely on the logic within the class, making
tests precise.

Mockito in Spring Boot


 Mocks repositories and services in Spring Boot applications.
 Injects mocks directly into the Spring context with
@MockBean.

Mocking Objects with Mockito


You can mock classes or interfaces using @Mock or Mockito.mock().
Example 1: Mocking with @Mock
 Use: Annotate a field with @Mock to create a mock object.

Example 2: Mocking with Mockito.mock()


 Use: Directly create a mock instance using Mockito.mock().
Injecting Mocks with @InjectMocks
 Use @InjectMocks to inject mocked dependencies into the class you are
testing.

Using Mockito in JUnit 5


In JUnit 5, you need to use @ExtendWith(MockitoExtension.class) to enable
Mockito annotations (@Mock, @InjectMocks, etc.):
Mockito Behavior Simulation
You can define how mocks should behave using when() and thenReturn().
when(mock.someMethod()).thenReturn(someValue); // When someMethod() is
called, return someValue
Example:
when(userRepository.findById(1)).thenReturn(Optional.of(new User("John Doe")));
// Simulate repository behavior

Using @MockBean in Spring Boot Tests

When testing Spring Boot components, use @MockBean to mock beans


within the Spring application context.

import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
class UserServiceTest {

@MockBean
private UserRepository userRepository; // Mock the repository bean

@Autowired
private MockMvc mockMvc; // Autowire MockMvc for making HTTP requests in
tests

@Test
void testAddUser() {
User user = new User("John Doe");

// Simulate repository behavior


when(userRepository.save(user)).thenReturn(user);

// Test the controller or service logic

mockMvc.perform(post("/users").contentType(MediaType.APPLICATION_JSON).cont
ent(asJsonString(user)))
.andExpect(status().isOk());
}
}

Essential Mockito annotations

@Mock
Purpose: Creates a mock object for a class or interface.
Use Case: Replace real dependencies with mocks.
Example:
@Mock
UserRepository userRepository;

@Spy
Purpose: Creates a partial mock – real methods are called unless stubbed.
Use Case: Use real object but override specific methods.
Example:
@Spy
List<String> list = new ArrayList<>();

@InjectMocks
Purpose: Injects mock or spy dependencies into the class being tested.
Use Case: Automatically injects mocks into the class under test.
Example:
@InjectMocks
UserService userService;

@Captor
Purpose: Captures arguments passed to mocked methods.
Use Case: Verifies arguments during method calls.
Example:
@Captor
ArgumentCaptor<User> captor;

@MockBean (Spring Boot Specific)


Purpose: Replaces a bean in the Spring context with a mock.
Use Case: Mock dependencies in Spring Boot integration tests.
Example:
@MockBean
UserRepository userRepository;

@SpyBean (Spring Boot Specific)


Purpose: Wraps an existing Spring bean with a spy.
Use Case: Spy on actual Spring beans.
Example:
@SpyBean
UserService userService;

@RunWith(MockitoJUnitRunner.class)
Purpose: Initializes mocks automatically.
Use Case: Ensures all mocks/spies are initialized before tests run.
Example:
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
}

@ExtendWith(MockitoExtension.class)
Purpose: JUnit 5 equivalent of @RunWith for initializing mocks.
Use Case: Initializes mocks in JUnit 5 tests.
Example:

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {
}

Annotation Workflow
@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

@Mock
UserRepository userRepository;

@InjectMocks
UserService userService;

@Captor
ArgumentCaptor<User> captor;

@Test
void testService() {
when(userRepository.findById(1)).thenReturn(new User(1, "John"));
userService.getUserName(1);
verify(userRepository).findById(captor.capture());
}
}

You might also like