Loading

Quipoin Menu

Learn • Practice • Grow

spring / Unit Testing with JUnit and Mockito
tutorial

Unit Testing with JUnit and Mockito

Imagine you're building a car. Before putting it on the road, you test each component individually – engine, brakes, lights. Unit testing is exactly that: testing individual components (methods) of your application in isolation.

JUnit is the most popular framework for writing unit tests in Java. Mockito helps you create mock objects to isolate the class you're testing.

Add Dependencies:


<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

Basic JUnit Test:


import static org.junit.jupiter.api.Assertions.*;

public class CalculatorTest {

private Calculator calculator = new Calculator();

@Test
public void testAdd() {
int result = calculator.add(5, 3);
assertEquals(8, result, "5 + 3 should be 8");
}

@Test
public void testDivideByZero() {
assertThrows(ArithmeticException.class, () -> {
calculator.divide(10, 0);
});
}
}

Testing Service Layer with Mockito:


@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

@Mock
private UserRepository userRepository;

@InjectMocks
private UserService userService;

@Test
public void testGetUserById() {
// Arrange
Long userId = 1L;
User mockUser = new User(userId, "John", "john@example.com");
when(userRepository.findById(userId)).thenReturn(Optional.of(mockUser));

// Act
User result = userService.getUserById(userId);

// Assert
assertNotNull(result);
assertEquals("John", result.getName());
verify(userRepository, times(1)).findById(userId);
}

@Test
public void testGetUserByIdNotFound() {
// Arrange
Long userId = 99L;
when(userRepository.findById(userId)).thenReturn(Optional.empty());

// Act & Assert
assertThrows(RuntimeException.class, () -> {
userService.getUserById(userId);
});
}
}

Testing Controllers with MockMvc:


@WebMvcTest(UserController.class)
public class UserControllerTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private UserService userService;

@Test
public void testGetUser() throws Exception {
User user = new User(1L, "John", "john@example.com");
when(userService.getUserById(1L)).thenReturn(user);

mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is("John")))
.andExpect(jsonPath("$.email", is("john@example.com")));
}
}
Two Minute Drill
  • Unit tests test individual components in isolation.
  • JUnit provides annotations: @Test, @BeforeEach, @AfterEach.
  • Assertions: assertEquals, assertTrue, assertThrows.
  • Mockito creates mocks: @Mock, @InjectMocks.
  • when().thenReturn() defines mock behavior.
  • verify() checks if methods were called.

Need more clarification?

Drop us an email at career@quipoinfotech.com