50 Spring Unit Testing interview questions with answers
Here is a list of 50 Spring Unit Testing interview questions with answers to help you prepare:
1. Basic Questions
What is unit testing, and why is it important?
- Unit testing involves testing individual components of a program to ensure they work as expected. It helps catch bugs early, improves code quality, and facilitates refactoring.
What is the difference between unit testing and integration testing?
- Unit testing focuses on isolated components, while integration testing checks the interaction between multiple components.
Why is unit testing critical in Spring applications?
- Spring applications rely on dependency injection and configurations, so unit testing ensures that beans and dependencies behave correctly in isolation.
What are the key annotations for unit testing in Spring?
@Test
,@MockBean
,@ExtendWith
,@SpringBootTest
,@ContextConfiguration
, and@WebMvcTest
.
What is the purpose of the
@SpringBootTest
annotation?- It loads the full application context, making it suitable for integration tests rather than pure unit tests.
How does
@ContextConfiguration
help in testing?- It loads specific configurations, allowing you to test a subset of the application context.
What is the
@Test
annotation used for?- It marks a method as a test case in both JUnit 4 and 5.
Explain the use of
@BeforeEach
and@AfterEach
.@BeforeEach
: Runs before each test method; used for setup.@AfterEach
: Runs after each test method; used for cleanup.
What is the difference between JUnit 4 and JUnit 5?
- JUnit 5 provides better modularity with
jupiter
and supports Java 8+ features, unlike the monolithic JUnit 4.
- JUnit 5 provides better modularity with
How can you run unit tests in Spring Boot applications?
- Using tools like Maven (
mvn test
), Gradle, or directly in IDEs like IntelliJ or Eclipse.
- Using tools like Maven (
2. Dependency Injection and Mocking
How do you mock dependencies in Spring?
- Using
@MockBean
with Spring or mocking libraries like Mockito.
- Using
What is the role of
@MockBean
?- It provides mock instances of Spring beans, overriding the actual beans in the application context.
How is
@Mock
different from@MockBean
?@Mock
is a pure Mockito feature, while@MockBean
integrates Mockito with Spring.
What is the purpose of
@InjectMocks
?- It injects mock dependencies into a class being tested.
How can you test a Spring component with dependencies?
- By mocking the dependencies and injecting them using
@InjectMocks
or@MockBean
.
- By mocking the dependencies and injecting them using
Explain
Mockito.when()
andthenReturn()
.when()
sets up behavior for a mocked method, andthenReturn()
specifies the return value.
How do you verify interactions with a mock object?
- Using
Mockito.verify()
.
- Using
What is the difference between
@Spy
and@Mock
?@Spy
creates a partial mock, preserving the original object behavior, while@Mock
creates a complete mock.
How do you handle exceptions in mocked methods?
- Using
Mockito.when(...).thenThrow()
.
- Using
Can you mock static methods in Spring tests?
- Yes, using tools like PowerMock or Mockito (since version 3.4+ with
mockStatic
).
- Yes, using tools like PowerMock or Mockito (since version 3.4+ with
3. Spring Boot Testing Annotations
What is the purpose of
@WebMvcTest
?- It loads only the web layer (e.g., controllers) for testing.
What does
@DataJpaTest
do?- It configures tests for JPA components with an embedded database.
When would you use
@TestConfiguration
?- To provide test-specific beans in the application context.
What is
@AutoConfigureMockMvc
used for?- It auto-configures
MockMvc
for testing web applications.
- It auto-configures
How is
@RestClientTest
helpful?- It simplifies testing REST clients like
RestTemplate
orWebClient
.
- It simplifies testing REST clients like
How does
@ParameterizedTest
improve testing?- It allows running the same test with multiple inputs using JUnit 5.
What is
@Transactional
used for in testing?- Ensures that tests roll back database changes automatically.
What is
@Rollback
, and how does it differ from@Transactional
?@Rollback
explicitly controls transaction rollback behavior, while@Transactional
applies general transaction management.
Explain
@Captor
in Mockito.- It captures arguments passed to a mock for verification.
What is
@TestPropertySource
?- It allows you to specify custom property files for tests.
4. Advanced Questions
How do you test private methods in Spring beans?
- By testing them indirectly through public methods or using reflection (not recommended).
How can you test a Spring
@Async
method?- Using
CompletableFuture
or mockingTaskExecutor
.
- Using
What is the difference between
MockMvc
andWebTestClient
?MockMvc
is for servlet-based apps, whileWebTestClient
is for reactive apps.
How do you test Spring Security in your application?
- Using
@WithMockUser
,@WithAnonymousUser
, or configuringMockMvc
with Spring Security.
- Using
What is
RestAssured
, and how is it used in testing?- It’s a library for testing RESTful APIs by simplifying HTTP request/response testing.
How do you test database-related logic in Spring?
- Using
@DataJpaTest
, in-memory databases (H2), and repository mocks.
- Using
How do you write tests for scheduled tasks in Spring?
- Use
@Test
with mocking or manual triggering ofScheduledExecutorService
.
- Use
How do you ensure test isolation in Spring tests?
- Use in-memory databases, reset mocks, and avoid shared state between tests.
What is Spring's
TestRestTemplate
?- A utility for making HTTP requests in integration tests.
What is
@DirtiesContext
, and when would you use it?- It resets the application context after a test to avoid context pollution.
5. Debugging and Performance
How do you debug a failing Spring test?
- Use IDE debugging tools, logs, and ensure proper application context setup.
What are flaky tests, and how do you handle them?
- Flaky tests have inconsistent results; resolve by identifying root causes (e.g., improper mocks or timing issues).
What tools can you use for test coverage analysis?
- Tools like JaCoCo, SonarQube, and IntelliJ’s built-in coverage tools.
How do you measure the performance of unit tests?
- Use JUnit's
@Timeout
or external profilers.
- Use JUnit's
What is the purpose of
@Repeat
in testing?- It reruns a test multiple times to check for flakiness or concurrency issues.
How do you test applications that rely on external APIs?
- By mocking API calls with tools like
WireMock
orMockRestServiceServer
.
- By mocking API calls with tools like
How do you deal with circular dependencies in Spring tests?
- Refactor the application to eliminate circular dependencies or mock problematic beans.
What is the role of
TestEntityManager
?- Simplifies JPA testing by providing an interface to perform database operations during tests.
How do you ensure tests are thread-safe?
- Avoid shared state, use local variables, and ensure thread-safe mocks.
What is the role of
SpringExtension
in JUnit 5?- It integrates Spring's testing support with JUnit 5 by enabling dependency injection in tests.
This list provides a broad spectrum of questions ranging from basics to advanced concepts to help prepare thoroughly.