Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
Chaturmind
← Java Interview Prep: Fresher to 2 Years

Java Basics, JVM & Memory

  • JDK, JRE, JVM & the main Method — Interview Questions
  • JVM Memory & Garbage Collection — Interview Questions
  • Data Types, Wrapper Classes & Equality — Interview Questions

Object-Oriented Programming

  • Classes, Objects, Packages & Access Modifiers — Interview Questions
  • Inheritance, Composition, this & super — Interview Questions
  • Polymorphism, Overloading & Overriding — Interview Questions
  • Abstraction, Interfaces & Encapsulation — Interview Questions
  • Constructors, Singleton, Anonymous Classes & Immutability — Interview Questions
  • Design Patterns & SOLID Basics — Interview Questions

Strings, Keywords, Exceptions & Serialization

  • Strings, String Pool, StringBuilder & StringBuffer — Interview Questions
  • static & final Keywords — Interview Questions
  • Exceptions, Generics, Enums & Reflection — Interview Questions
  • Serialization & transient — Interview Questions

Collections Framework

  • Collections Framework Basics — Interview Questions
  • HashMap, HashSet & TreeMap Internals — Interview Questions

Multithreading Basics

  • Threads, Synchronization & volatile Basics — Interview Questions

Java 8+ & Stream API

  • Java 8 to Java 21 Features — Interview Questions
  • Stream API Coding Questions (Part 1) — Interview Questions
  • Stream API Coding Questions (Part 2) — Interview Questions

Coding Round Programs

  • Classic Number & String Programs — Interview Questions
  • String & Collection Programs — Interview Questions
  • Array & String Problem Solving — Interview Questions

Spring Framework Core

  • Spring IoC, Dependency Injection & Beans — Interview Questions
  • Spring Injection Types, Scopes, Profiles & WebFlux — Interview Questions

Spring Boot Essentials

  • Spring Boot Fundamentals — Interview Questions
  • Spring Boot Runners, Servers & Configuration — Interview Questions
  • Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions
  • Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions
  • REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

Spring MVC

  • Spring MVC Architecture & DispatcherServlet — Interview Questions
  • Spring MVC Request Mapping & Controllers — Interview Questions
  • Spring MVC Forms, Views & Interceptors — Interview Questions
  • Spring MVC Exceptions, Security & Dependency Injection — Interview Questions
  • Spring MVC Data Binding, Static Resources & Path Variables — Interview Questions
  • Spring MVC i18n, Testing, File Uploads & Scaling — Interview Questions

Hibernate & Spring Data JPA

  • Hibernate & JPA Core Concepts — Interview Questions
  • Hibernate Performance, Mapping & Scenarios — Interview Questions

SQL

  • SQL Basics, Keys, Normalization & Transactions — Interview Questions
  • SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions
  • SQL "Difference Between" Questions — Interview Questions
  • SQL Query Writing (Part 1) — Interview Questions
  • SQL Query Writing (Part 2) — Interview Questions

Microservices Basics

  • Microservices, API Gateway & Communication — Interview Questions
  • Service Discovery, Data Consistency & Deployment — Interview Questions
  • Microservices Monitoring, Security & Resilience — Interview Questions

Maven & Git

  • Maven — Interview Questions
  • Git — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: Fresher to 2 YearsSpring Boot Essentials
✓ FreeBeginner· 7 min read

Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions

Testing a Boot app (unit, slice and integration tests), unit testing purpose, JUnit and Mockito, @Mock vs @InjectMocks, @SpringBootTest, global exception handling, pom.xml, auto-configuration and customising or disabling it, the starter parent and starters.

Published September 25, 2026


How to use this lesson

Testing questions reveal whether you've worked on a real codebase. Describe the test pyramid: fast unit tests with Mockito, focused slice tests, and a few full @SpringBootTest integration tests. Then explain why each layer exists.

Q1. How do you test a Spring Boot application?

Short answer: In layers:

  • Unit tests: plain JUnit 5 plus Mockito, with no Spring context. They're fast, and test business logic.
  • Slice tests: load only one layer.
    • @WebMvcTest for controllers, with MockMvc.
    • @DataJpaTest for repositories, against an embedded database or Testcontainers.
    • @JsonTest for serialisation.
  • Integration tests: @SpringBootTest loads the full context, often with Testcontainers for a real database or Kafka.
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mvc;
    @MockitoBean OrderService service;          // Boot 3.4+ (older versions: @MockBean)

    @Test void returnsOrder() throws Exception {
        when(service.find(1L)).thenReturn(new OrderDto(1L, "PAID"));
        mvc.perform(get("/api/orders/1"))
           .andExpect(status().isOk())
           .andExpect(jsonPath("$.status").value("PAID"));
    }
}

Learn it in depth → Spring Exception Handling

Q2. What is the purpose of unit testing?

Short answer: To verify that small units of code (a method or a class) behave correctly in isolation. It catches bugs early, documents the intended behaviour, and gives you the confidence to refactor. Good unit tests are fast, deterministic and independent of each other.

Key points to cover:

  • A useful structure is Arrange–Act–Assert (or Given–When–Then), with one behaviour per test.
  • Test the edge cases (empty input, boundaries, error paths), not just the happy path.

Q3. How do JUnit and Mockito help with unit testing?

Short answer: JUnit 5 is the test framework. It provides @Test, assertions, the lifecycle (@BeforeEach), parameterised tests, and the runner. Mockito creates mock objects for a class's dependencies, so you can stub their behaviour (when(...).thenReturn(...)) and verify interactions (verify(...)) without a real database or HTTP call.

@ExtendWith(MockitoExtension.class)
class CheckoutServiceTest {
    @Mock PaymentGateway gateway;
    @Mock OrderRepository orders;
    @InjectMocks CheckoutService checkout;

    @Test void failedPaymentDoesNotSaveOrder() {
        when(gateway.charge(any())).thenReturn(PaymentResult.declined("insufficient funds"));
        assertThrows(PaymentDeclinedException.class, () -> checkout.placeOrder(sampleCart()));
        verify(orders, never()).save(any());
    }
}

Q4. What's the difference between @Mock and @InjectMocks?

Short answer: @Mock creates a fake dependency. @InjectMocks creates the real object under test, and injects the @Mock fields into it, through the constructor, setters or fields.

Key points to cover:

  • @InjectMocks fails silently when it can't match a dependency: the field is simply left null. With constructor injection, you can instead write checkout = new CheckoutService(gateway, orders) in @BeforeEach, which is explicit and fails loudly.
  • @Spy wraps a real object, where only the stubbed methods are faked. Use it sparingly.

Q5. What is the role of @SpringBootTest?

Short answer: It starts the full application context: all beans, auto-configuration and properties. That lets you test how components work together. With webEnvironment = RANDOM_PORT, it also starts the embedded server, for real HTTP tests.

Key points to cover:

  • It's slower than slice tests. Spring caches contexts between test classes that share the same configuration, so avoid needlessly different @MockitoBean setups, which force the context to be rebuilt.
  • Pair it with Testcontainers (@ServiceConnection, Boot 3.1+) for realistic databases and brokers.

Q6. How do you handle exceptions in a Spring Boot application?

Short answer: Centralise error handling in a @RestControllerAdvice class, with @ExceptionHandler methods that map exceptions to HTTP responses. Use Problem Details (RFC 9457, ProblemDetail), so that clients get a consistent JSON error format.

@RestControllerAdvice
class ApiExceptionHandler {
    @ExceptionHandler(OrderNotFoundException.class)
    ProblemDetail notFound(OrderNotFoundException ex) {
        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
        pd.setTitle("Order not found");
        return pd;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    ProblemDetail invalid(MethodArgumentNotValidException ex) {
        ProblemDetail pd = ProblemDetail.forStatus(HttpStatus.BAD_REQUEST);
        pd.setProperty("errors", ex.getBindingResult().getFieldErrors().stream()
                .map(e -> e.getField() + ": " + e.getDefaultMessage()).toList());
        return pd;
    }
}

Key points to cover:

  • Never leak stack traces or internal messages to clients. Log them on the server, together with a correlation ID.

Learn it in depth → Spring Exception Handling

Q7. What is the purpose of pom.xml in a Maven project?

Short answer: It's the Project Object Model. It declares the project's coordinates (groupId, artifactId, version), packaging, dependencies, plugins, build settings, properties and profiles. Maven reads it to download dependencies, compile, test and package the application.

Learn it in depth → Maven Interview Questions

Q8. What role does auto-configuration play in a Spring Boot application?

Short answer: It creates the infrastructure beans your app needs, based on what's on the classpath and in your properties.

  • spring-boot-starter-data-jpa plus a JDBC URL gives you a DataSource, an EntityManagerFactory and a transaction manager.
  • spring-boot-starter-web gives you Tomcat, the DispatcherServlet and Jackson.

It all backs off wherever you define your own beans.

Learn it in depth → Auto-Configuration Mechanism

Q9. Can you customise a specific auto-configuration?

Short answer: Yes, in increasing order of control:

  1. Properties (spring.datasource.hikari.maximum-pool-size, spring.jackson.default-property-inclusion).
  2. Customiser beans (Jackson2ObjectMapperBuilderCustomizer, WebServerFactoryCustomizer), which tweak the auto-configured bean without replacing it.
  3. Your own bean of the same type, which makes the auto-configuration back off.
  4. Excluding the auto-configuration entirely.

Key points to cover:

  • You can also write your own auto-configuration for a shared company library, using @AutoConfiguration plus @Conditional… annotations, registered in the AutoConfiguration.imports file.

Q10. How do you disable specific auto-configuration classes?

Short answer: Use @SpringBootApplication(exclude = DataSourceAutoConfiguration.class), or excludeName with a fully qualified class name, or the spring.autoconfigure.exclude property (which can differ per profile).

Learn it in depth → Spring Boot Runners, Servers & Configuration

Q11. What is the purpose of spring-boot-starter-parent?

Short answer: It's a Maven parent POM that provides:

  • dependency management, through the Boot BOM;
  • a sensible Java version and UTF-8 encoding;
  • plugin configuration (compiler with -parameters, surefire, the Spring Boot plugin's repackage goal);
  • resource filtering for application*.yml.

Key points to cover:

  • If your project already has a corporate parent, import spring-boot-dependencies in <dependencyManagement> with <scope>import</scope> instead. You get the version management without the parent.

Q12. How do starters simplify Maven or Gradle configuration?

Short answer: One starter replaces a list of individually chosen, individually versioned dependencies. For example, spring-boot-starter-web brings Spring MVC, Jackson, validation support and embedded Tomcat. It also triggers the matching auto-configuration, so adding a dependency is often all it takes to enable a feature.

Follow-up questions this topic invites — and their answers

Q: What is Testcontainers, and why use it? A: A library that starts real dependencies (PostgreSQL, Kafka, Redis) in Docker containers during tests. You test against the real database, rather than an in-memory stand-in with different SQL behaviour.

Q: @MockBean vs @Mock? A: @Mock (Mockito) creates a mock for a plain unit test. @MockBean (now @MockitoBean) replaces a bean inside the Spring context with a mock, so it's used in slice and integration tests.

Q: How do you test a repository? A: With @DataJpaTest. It configures JPA, repositories and an embedded or Testcontainers database, and rolls back after each test. Test your custom queries there, not the built-in CRUD methods.

Q: What does @Transactional on a test do? A: Each test runs in a transaction that is rolled back at the end, which keeps tests isolated. Be careful: rollback can hide problems that only appear on commit, such as constraint checks or flush-time errors.

Previous

Spring Boot Controllers, Profiles, Actuator & DevTools — Interview Questions

Next

REST APIs, Swagger, Embedded Servers & Key Annotations — Interview Questions

AI Tutor

Lesson: Spring Boot Testing, Exceptions & Auto-Configuration — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.