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

  1. 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.
  2. 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.
  3. 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.
  4. What are the key annotations for unit testing in Spring?

    • @Test, @MockBean, @ExtendWith, @SpringBootTest, @ContextConfiguration, and @WebMvcTest.
  5. 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.
  6. How does @ContextConfiguration help in testing?

    • It loads specific configurations, allowing you to test a subset of the application context.
  7. What is the @Test annotation used for?

    • It marks a method as a test case in both JUnit 4 and 5.
  8. 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.
  9. 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.
  10. 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.

2. Dependency Injection and Mocking

  1. How do you mock dependencies in Spring?

    • Using @MockBean with Spring or mocking libraries like Mockito.
  2. What is the role of @MockBean?

    • It provides mock instances of Spring beans, overriding the actual beans in the application context.
  3. How is @Mock different from @MockBean?

    • @Mock is a pure Mockito feature, while @MockBean integrates Mockito with Spring.
  4. What is the purpose of @InjectMocks?

    • It injects mock dependencies into a class being tested.
  5. How can you test a Spring component with dependencies?

    • By mocking the dependencies and injecting them using @InjectMocks or @MockBean.
  6. Explain Mockito.when() and thenReturn().

    • when() sets up behavior for a mocked method, and thenReturn() specifies the return value.
  7. How do you verify interactions with a mock object?

    • Using Mockito.verify().
  8. What is the difference between @Spy and @Mock?

    • @Spy creates a partial mock, preserving the original object behavior, while @Mock creates a complete mock.
  9. How do you handle exceptions in mocked methods?

    • Using Mockito.when(...).thenThrow().
  10. Can you mock static methods in Spring tests?

    • Yes, using tools like PowerMock or Mockito (since version 3.4+ with mockStatic).

3. Spring Boot Testing Annotations

  1. What is the purpose of @WebMvcTest?

    • It loads only the web layer (e.g., controllers) for testing.
  2. What does @DataJpaTest do?

    • It configures tests for JPA components with an embedded database.
  3. When would you use @TestConfiguration?

    • To provide test-specific beans in the application context.
  4. What is @AutoConfigureMockMvc used for?

    • It auto-configures MockMvc for testing web applications.
  5. How is @RestClientTest helpful?

    • It simplifies testing REST clients like RestTemplate or WebClient.
  6. How does @ParameterizedTest improve testing?

    • It allows running the same test with multiple inputs using JUnit 5.
  7. What is @Transactional used for in testing?

    • Ensures that tests roll back database changes automatically.
  8. What is @Rollback, and how does it differ from @Transactional?

    • @Rollback explicitly controls transaction rollback behavior, while @Transactional applies general transaction management.
  9. Explain @Captor in Mockito.

    • It captures arguments passed to a mock for verification.
  10. What is @TestPropertySource?

    • It allows you to specify custom property files for tests.

4. Advanced Questions

  1. How do you test private methods in Spring beans?

    • By testing them indirectly through public methods or using reflection (not recommended).
  2. How can you test a Spring @Async method?

    • Using CompletableFuture or mocking TaskExecutor.
  3. What is the difference between MockMvc and WebTestClient?

    • MockMvc is for servlet-based apps, while WebTestClient is for reactive apps.
  4. How do you test Spring Security in your application?

    • Using @WithMockUser, @WithAnonymousUser, or configuring MockMvc with Spring Security.
  5. What is RestAssured, and how is it used in testing?

    • It’s a library for testing RESTful APIs by simplifying HTTP request/response testing.
  6. How do you test database-related logic in Spring?

    • Using @DataJpaTest, in-memory databases (H2), and repository mocks.
  7. How do you write tests for scheduled tasks in Spring?

    • Use @Test with mocking or manual triggering of ScheduledExecutorService.
  8. How do you ensure test isolation in Spring tests?

    • Use in-memory databases, reset mocks, and avoid shared state between tests.
  9. What is Spring's TestRestTemplate?

    • A utility for making HTTP requests in integration tests.
  10. 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

  1. How do you debug a failing Spring test?

    • Use IDE debugging tools, logs, and ensure proper application context setup.
  2. 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).
  3. What tools can you use for test coverage analysis?

    • Tools like JaCoCo, SonarQube, and IntelliJ’s built-in coverage tools.
  4. How do you measure the performance of unit tests?

    • Use JUnit's @Timeout or external profilers.
  5. What is the purpose of @Repeat in testing?

    • It reruns a test multiple times to check for flakiness or concurrency issues.
  6. How do you test applications that rely on external APIs?

    • By mocking API calls with tools like WireMock or MockRestServiceServer.
  7. How do you deal with circular dependencies in Spring tests?

    • Refactor the application to eliminate circular dependencies or mock problematic beans.
  8. What is the role of TestEntityManager?

    • Simplifies JPA testing by providing an interface to perform database operations during tests.
  9. How do you ensure tests are thread-safe?

    • Avoid shared state, use local variables, and ensure thread-safe mocks.
  10. 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.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete