Testing
Unit Test
Dependency
spring-boot-starter-test
Mockito
Annotation
@Mock
: Create a mock dependency.@Spy
: Use the real dependency.@InjectMocks
: Class under test.
Sample Code
@ExtendWith(MockitoExtension.class) // Enables Mockito annotations
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
void shouldFindUserByIdWhenUserExists() {
// ...
}
}
Integration Test
Dependency
spring-boot-starter-test
- H2 in-memory database
Sample Code
- Controller Test:
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldCreateUser() throws Exception {
// Arrange
String userJson = "{\"name\":\"Alice\",\"email\":\"alice@example.com\"}";
// Act & Assert
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(userJson))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name").value("Alice"))
.andExpect(jsonPath("$.email").value("alice@example.com"));
}
}