Quiz: Spring Boot Tests
Test your knowledge on JUnit 5, Mockito, and integration tests.
30 questions - Click on each question to reveal the answer.
Questions 1-10: JUnit 5
Question 1: What are the basic JUnit 5 annotations?
Answer:
| Annotation | Description |
|---|---|
@Test | Marks a test method |
@BeforeEach | Before each test |
@AfterEach | After each test |
@BeforeAll | Before all tests (static) |
@AfterAll | After all tests (static) |
@Disabled | Disables a test |
@DisplayName | Readable name |
Question 2: How to structure a test with the AAA pattern?
Answer: Arrange-Act-Assert:
@Test
void shouldCalculateTotal() {
// Arrange (Given)
Order order = new Order();
order.addItem(new Item("Book", 10.0));
order.addItem(new Item("Pen", 2.0));
// Act (When)
double total = order.calculateTotal();
// Assert (Then)
assertEquals(12.0, total);
}
Question 3: What assertions to use with AssertJ?
Answer:
import static org.assertj.core.api.Assertions.*;
assertThat(result).isEqualTo(expected);
assertThat(list).hasSize(3);
assertThat(list).contains("item");
assertThat(user.getName()).isNotBlank();
assertThat(price).isGreaterThan(0);
assertThatThrownBy(() -> service.process(null))
.isInstanceOf(IllegalArgumentException.class);
Question 4: How to test an exception?
Answer:
// JUnit 5
@Test
void shouldThrowException() {
assertThrows(IllegalArgumentException.class, () -> {
service.process(null);
});
}
// AssertJ
@Test
void shouldThrowException() {
assertThatThrownBy(() -> service.process(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("cannot be null");
}
Question 5: How to run a test multiple times with different parameters?
Answer:
@ParameterizedTest
@ValueSource(strings = {"a@b.com", "test@domain.org"})
void shouldValidateEmail(String email) {
assertTrue(validator.isValidEmail(email));
}
@ParameterizedTest
@CsvSource({
"1, 2, 3",
"5, 5, 10",
"0, 0, 0"
})
void shouldAdd(int a, int b, int expected) {
assertEquals(expected, calculator.add(a, b));
}
Question 6: How to group tests?
Answer:
@Nested
@DisplayName("When user is logged in")
class WhenLoggedIn {
@BeforeEach
void setup() {
login();
}
@Test
void canAccessProfile() { }
@Test
void canLogout() { }
}
@Nested
@DisplayName("When user is anonymous")
class WhenAnonymous {
@Test
void cannotAccessProfile() { }
}
Question 7: How to disable a test conditionally?
Answer:
@Test
@EnabledOnOs(OS.LINUX)
void onlyOnLinux() { }
@Test
@EnabledIfEnvironmentVariable(named = "ENV", matches = "CI")
void onlyInCI() { }
@Test
@DisabledIf("isWeekend")
void notOnWeekend() { }
boolean isWeekend() {
return LocalDate.now().getDayOfWeek().getValue() > 5;
}
Question 8: How to give a timeout to a test?
Answer:
@Test
@Timeout(value = 5, unit = TimeUnit.SECONDS)
void shouldCompleteInTime() {
// Test that should finish in less than 5 seconds
}
// Or with assertTimeout
@Test
void shouldCompleteInTime() {
assertTimeout(Duration.ofSeconds(2), () -> {
service.longOperation();
});
}
Question 9: How to reuse configuration between tests?
Answer:
// Base class
abstract class BaseTest {
@BeforeEach
void commonSetup() {
// Common configuration
}
}
class UserServiceTest extends BaseTest {
@Test
void testUser() { }
}
// Or with Extension
@ExtendWith(DatabaseExtension.class)
class DatabaseTest { }
Question 10: How to run tests in a specific order?
Answer:
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class OrderedTest {
@Test
@Order(1)
void createUser() { }
@Test
@Order(2)
void updateUser() { }
@Test
@Order(3)
void deleteUser() { }
}
Note: avoid dependent tests if possible!
Questions 11-20: Mockito
Question 11: How to create a mock with Mockito?
Answer:
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
// Or manually
UserRepository repo = mock(UserRepository.class);
}
Question 12: How to define the behavior of a mock?
Answer:
// Return a value
when(userRepository.findById(1L)).thenReturn(Optional.of(user));
// Throw an exception
when(userRepository.findById(999L)).thenThrow(new NotFoundException());
// Dynamic response
when(userRepository.save(any(User.class))).thenAnswer(invocation -> {
User u = invocation.getArgument(0);
u.setId(1L);
return u;
});
Question 13: How to verify that a method was called?
Answer:
// Verify the call
verify(userRepository).save(any(User.class));
// Verify the number of calls
verify(userRepository, times(2)).findById(anyLong());
verify(userRepository, never()).delete(any());
verify(userRepository, atLeast(1)).findAll();
Question 14: What is the difference between @Mock and @Spy?
Answer:
@Mock: creates a fake object, all methods return null/0/false@Spy: uses the real object, can override certain methods
@Spy
private UserService userService = new UserService();
// Only this method is mocked
doReturn(user).when(userService).findById(1L);
// Other methods execute real code
Question 15: How to capture arguments passed to a mock?
Answer:
@Captor
ArgumentCaptor<User> userCaptor;
@Test
void shouldCaptureUser() {
userService.createUser(request);
verify(userRepository).save(userCaptor.capture());
User savedUser = userCaptor.getValue();
assertThat(savedUser.getEmail()).isEqualTo("test@example.com");
}
Question 16: How to mock a void method?
Answer:
// Do nothing (default)
doNothing().when(emailService).sendEmail(any());
// Throw an exception
doThrow(new MailException()).when(emailService).sendEmail(any());
// Execute code
doAnswer(invocation -> {
String email = invocation.getArgument(0);
log.info("Would send email to: {}", email);
return null;
}).when(emailService).sendEmail(any());
Question 17: How to mock static methods?
Answer:
@Test
void testStaticMethod() {
try (MockedStatic<UUID> mockedUUID = mockStatic(UUID.class)) {
UUID fakeUUID = UUID.fromString("123e4567-e89b-12d3-a456-426614174000");
mockedUUID.when(UUID::randomUUID).thenReturn(fakeUUID);
// Test
String id = service.generateId();
assertThat(id).contains("123e4567");
}
}
Question 18: How to verify the order of calls?
Answer:
@Test
void shouldCallInOrder() {
service.process();
InOrder inOrder = inOrder(validator, repository, notifier);
inOrder.verify(validator).validate(any());
inOrder.verify(repository).save(any());
inOrder.verify(notifier).notify(any());
}
Question 19: How to use Mockito matchers?
Answer:
when(repo.findByName(anyString())).thenReturn(user);
when(repo.findByAge(eq(25))).thenReturn(users);
when(repo.search(argThat(s -> s.length() > 3))).thenReturn(results);
verify(repo).save(argThat(user ->
user.getEmail().contains("@") && user.getAge() > 18
));
Question 20: How to reset a mock between tests?
Answer:
@AfterEach
void resetMocks() {
reset(userRepository);
}
// Or for a specific mock
Mockito.clearInvocations(userRepository);
Questions 21-30: Integration Tests
Question 21: What annotation for a Spring Boot integration test?
Answer:
@SpringBootTest
class IntegrationTest {
// Loads the entire Spring context
}
// With web server
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class WebIntegrationTest { }
Question 22: How to test only the web layer?
Answer:
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void shouldReturnUser() throws Exception {
when(userService.findById(1L)).thenReturn(user);
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
Question 23: How to test only the repository layer?
Answer:
@DataJpaTest
class UserRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private UserRepository userRepository;
@Test
void shouldFindByEmail() {
User user = new User("test@example.com");
entityManager.persist(user);
entityManager.flush();
Optional<User> found = userRepository.findByEmail("test@example.com");
assertThat(found).isPresent();
}
}
Question 24: How to use TestRestTemplate?
Answer:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApiIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
void shouldCreateUser() {
UserRequest request = new UserRequest("test@example.com");
ResponseEntity<User> response = restTemplate.postForEntity(
"/api/users", request, User.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
}
}
Question 25: How to use a test database?
Answer:
// In-memory H2 (automatic with @DataJpaTest)
// Or Testcontainers
@Testcontainers
@SpringBootTest
class PostgresIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:15");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
}
Question 26: How to test with a specific profile?
Answer:
@SpringBootTest
@ActiveProfiles("test")
class TestProfileTest {
// Uses application-test.yml
}
# application-test.yml
spring:
datasource:
url: jdbc:h2:mem:testdb
Question 27: How to test security?
Answer:
@WebMvcTest(SecuredController.class)
@Import(SecurityConfig.class)
class SecurityTest {
@Test
void anonymousCannotAccess() throws Exception {
mockMvc.perform(get("/api/admin"))
.andExpect(status().isUnauthorized());
}
@Test
@WithMockUser(roles = "ADMIN")
void adminCanAccess() throws Exception {
mockMvc.perform(get("/api/admin"))
.andExpect(status().isOk());
}
}
Question 28: How to test validations?
Answer:
@Test
void shouldRejectInvalidEmail() throws Exception {
String invalidRequest = """
{"email": "not-an-email", "name": "John"}
""";
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(invalidRequest))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors.email").exists());
}
Question 29: How to measure code coverage?
Answer: With JaCoCo:
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.11</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
Report in target/site/jacoco/index.html
Question 30: What are the best testing practices?
Answer:
- One test = one behavior: no complex multi-assertions
- Independent tests: no dependencies between tests
- Descriptive names:
shouldReturnUserWhenValidId - Isolated data: each test prepares its data
- Mock external dependencies: API, email, etc.
- Avoid flaky tests: no time dependencies
- Test error cases: not just the happy path
- Reasonable coverage: aim for 70-80%, not 100%
Score
| Score | Level |
|---|---|
| 27-30 | Excellent - Mastered tests |
| 21-26 | Good - Some revisions needed |
| 15-20 | Average - Review the chapters |
| Less than 15 | Needs improvement |