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: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsSpring Boot In Depth & Scenarios
✓ FreeIntermediate· 9 min read

Spring Boot Testing, Error Pages & Deployment — Interview Questions

A testing strategy for Boot apps, @SpringBootTest and @MockBean/@MockitoBean, DevTools, mocking external services and whole microservices (WireMock, Testcontainers, contract tests), Docker images done well, JAR vs WAR, CI/CD integration, the Whitelabel page, handling 404s, and deploying to AWS or Azure.

Published September 25, 2026


How to use this lesson

This lesson covers the path from "it works on my machine" to "it runs in production". Interviewers want a testing pyramid you've actually used, a Docker image that isn't 800 MB running as root, and error handling that returns proper JSON instead of the Whitelabel page.

Q1. How do you approach testing a Spring Boot application?

Short answer: Use a test pyramid:

  • Many unit tests: JUnit 5 and Mockito, with no Spring context. They cover domain logic and services, and run in milliseconds.
  • Some slice tests that load only one layer:
    • @WebMvcTest for controllers (with MockMvc);
    • @DataJpaTest for repositories and queries;
    • @JsonTest for serialisation;
    • @RestClientTest for HTTP clients.
  • A few integration tests: @SpringBootTest with Testcontainers (a real PostgreSQL or Kafka), covering critical flows end to end.
  • Contract tests between services (Spring Cloud Contract or Pact).

Key points to cover:

  • Keep the Spring context cache effective: share one integration-test base configuration, and avoid unique @MockitoBean combinations in each class.

Learn it in depth → JUnit 5

Q2. How are @SpringBootTest and @MockBean used?

Short answer: @SpringBootTest boots the full application context. Add webEnvironment = RANDOM_PORT to start the real server, for HTTP tests with TestRestTemplate or WebTestClient. @MockBean (replaced by @MockitoBean in Boot 3.4 / Spring Framework 6.2) replaces a bean in that context with a Mockito mock. Use it for dependencies you don't want to exercise, such as a payment gateway client.

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Testcontainers
class CheckoutFlowIT {
    @Container @ServiceConnection
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");

    @MockitoBean PaymentGateway gateway;                 // replace only the external dependency
    @Autowired TestRestTemplate http;

    @Test void placesOrder() {
        when(gateway.charge(any())).thenReturn(PaymentResult.approved("pay_123"));
        var response = http.postForEntity("/api/orders", sampleOrder(), OrderResponse.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
    }
}

Q3. What is Spring Boot DevTools used for?

Short answer: DevTools speeds up local development:

  • Automatic restarts when classes change. It uses two class loaders, so only your code reloads, which is fast.
  • LiveReload, for browser refreshes.
  • Development-friendly defaults, such as template caching turned off.
  • Global settings.
  • Optional remote update support, which should never be used in production.

Key points to cover:

  • It's automatically disabled in a packaged production JAR. Declare it optional/developmentOnly, so it isn't shipped at all.

Q4. How do you mock external services in a Spring Boot test?

Short answer: Choose the level to mock at:

  • The bean level: @MockitoBean replaces your client bean (for example, PaymentGateway). It's fast, but it skips the HTTP and serialisation code.
  • The HTTP level: WireMock (or MockRestServiceServer for RestTemplate/RestClient) runs a fake HTTP server. Your real client code, timeouts, headers and JSON mapping are all exercised.
  • Infrastructure: Testcontainers for real databases, brokers or LocalStack (AWS).
@WireMockTest(httpPort = 8089)
class PaymentClientTest {
    @Test void mapsDeclines() {
        stubFor(post("/charges").willReturn(aResponse().withStatus(402)
                .withHeader("Content-Type", "application/json").withBody("{\"code\":\"card_declined\"}")));
        assertThrows(PaymentDeclinedException.class, () -> client.charge(sampleCharge()));
    }
}

Q5. How do you mock other microservices during testing?

Short answer:

  • Integration tests: WireMock stubs for the downstream services, which also let you simulate slow responses, 5xx errors and timeouts, to test resilience.
  • Contract testing: Pact (consumer-driven) or Spring Cloud Contract. The consumer's expectations become a contract that the provider's build verifies, so mocks can't silently drift from reality.
  • Higher environments: service virtualisation, or ephemeral environments with real dependencies.

Common trap: relying only on hand-written mocks. The consumer's tests pass while the real provider has changed its API. Contract tests close that gap.

Q6. How do you create a Docker image for a Spring Boot application?

Short answer: You have three options:

  1. Cloud Native Buildpacks: ./mvnw spring-boot:build-image. No Dockerfile is needed, and you get layered, reproducible, non-root images with memory-calculator tuning.
  2. Jib: builds optimised images without a Docker daemon.
  3. A multi-stage Dockerfile using Boot's layered JAR, so dependencies are cached separately from your code.
FROM eclipse-temurin:21-jdk AS build
WORKDIR /app
COPY . .
RUN ./mvnw -q package -DskipTests && java -Djarmode=tools -jar target/app.jar extract --layers --launcher --destination extracted

FROM eclipse-temurin:21-jre
RUN useradd --system app
USER app
WORKDIR /app
COPY --from=build /app/extracted/dependencies/ ./
COPY --from=build /app/extracted/spring-boot-loader/ ./
COPY --from=build /app/extracted/snapshot-dependencies/ ./
COPY --from=build /app/extracted/application/ ./
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "org.springframework.boot.loader.launch.JarLauncher"]

Key points to cover:

  • Use a JRE (not JDK) base image, run as a non-root user, and size the heap relative to the container limit (MaxRAMPercentage). Add health checks, and scan the image for vulnerabilities.

Learn it in depth → Multi-Stage Builds

Q7. How do you deploy a Spring Boot web app as a JAR, and as a WAR?

Short answer:

  • JAR (the default): ./mvnw package creates an executable fat JAR with an embedded server. Run it with java -jar app.jar, or containerise it.
  • WAR: set <packaging>war</packaging>, mark the embedded Tomcat starter as provided, and make the main class extend SpringBootServletInitializer (overriding configure). Then deploy the WAR to an external Tomcat, JBoss or WebLogic.
@SpringBootApplication
public class ShopApplication extends SpringBootServletInitializer {
    @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder b) { return b.sources(ShopApplication.class); }
    public static void main(String[] args) { SpringApplication.run(ShopApplication.class, args); }
}

Key points to cover:

  • A WAR built this way is also runnable with java -jar. Choose WAR only when the organisation mandates shared application servers.

Q8. How do you integrate a Spring Boot application with a CI/CD pipeline?

Short answer: A typical pipeline (GitHub Actions, GitLab CI or Jenkins):

  1. Build and unit test (./mvnw verify), with caching of ~/.m2.
  2. Static analysis and security: Checkstyle/Spotless, SonarQube, dependency scanning (OWASP, Snyk), and secret scanning.
  3. Integration tests with Testcontainers.
  4. Build and scan the image, tagged with the commit SHA, and push it to a registry.
  5. Deploy to staging (Helm or GitOps with Argo CD), and run smoke and contract tests.
  6. Promote the same image to production through canary or blue-green, with automated rollback on failing health checks or SLOs.

Key points to cover:

  • Build once, deploy everywhere. Environment differences come only from configuration, never from rebuilding.

Learn it in depth → CI/CD Pipeline Design

Q9. What is the Whitelabel error page, and how do you replace it?

Short answer: It's Spring Boot's default HTML error view, rendered by BasicErrorController at /error when an error isn't handled and no custom error page exists. Typical triggers are an unmapped URL (404) or an unhandled exception (500).

The fixes:

  • For APIs, handle exceptions in a @RestControllerAdvice, and return Problem Details JSON (spring.mvc.problemdetails.enabled=true).
  • For HTML apps, add templates such as templates/error/404.html, error/5xx.html or error.html.
  • Turn it off with server.error.whitelabel.enabled=false, if a proxy serves the error pages.

Key points to cover:

  • Never expose stack traces (server.error.include-stacktrace=never, the default in production).

Q10. How do you handle a 404 in Spring Boot?

Short answer:

  • For missing resources your code looks up (such as an order that doesn't exist), throw a domain exception (OrderNotFoundException), or ResponseStatusException(NOT_FOUND), and map it in @RestControllerAdvice.
  • For unmapped URLs, Spring Framework 6.1+ raises NoResourceFoundException. ResponseEntityExceptionHandler turns it into a 404 Problem Detail, or you can add your own @ExceptionHandler(NoResourceFoundException.class).
  • For HTML sites, add an error/404.html template. Or, as a last resort, implement a custom ErrorController for full control.
@RestControllerAdvice
class NotFoundAdvice {
    @ExceptionHandler({ OrderNotFoundException.class, NoResourceFoundException.class })
    ProblemDetail notFound(Exception ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "The requested resource does not exist");
    }
}

Learn it in depth → Spring Exception Handling

Q11. Scenario: deploy a Spring Boot app to AWS or Azure. What steps do you take, and how do you configure the different environments?

Short answer:

  1. Package a container image, or a JAR.
  2. Choose a runtime:
    • AWS: ECS/Fargate, EKS, Elastic Beanstalk, or App Runner.
    • Azure: App Service, Container Apps, or AKS.
  3. Provision the database, cache and network with IaC (Terraform), in private subnets.
  4. Configure the environments with environment variables plus profiles. Keep secrets in AWS Secrets Manager / Parameter Store or Azure Key Vault, accessed through the platform identity (IAM roles, Managed Identity), and never in property files.
  5. Health checks: point the load balancer at /actuator/health/readiness.
  6. Observability: logs to CloudWatch or Azure Monitor, metrics, tracing.
  7. Autoscaling policies.
  8. CI/CD with automated rollout and rollback.

Key points to cover:

  • Use the same image in every environment, with graceful shutdown for rolling deploys, and database migrations (Flyway) running as a controlled step.

Learn it in depth → AWS EC2

Follow-up questions this topic invites — and their answers

Q: Why are my @SpringBootTest tests slow? A: Usually because the context is rebuilt too often (a different @MockitoBean set, @DirtiesContext, or different properties per class), or because the full context starts where a slice test would do. Standardise the test configurations, and prefer slices.

Q: What does @ServiceConnection do? A: With Testcontainers (Boot 3.1+), it automatically wires the container's connection details (URL, username, password) into the application's configuration. You don't need @DynamicPropertySource boilerplate.

Q: How do you make container images smaller and faster to start? A: Use JRE or distroless base images, layered JARs, and jlink custom runtimes. Use Class Data Sharing and Spring AOT, or GraalVM native images, when startup time is critical (serverless).

Q: How should a deployment wait for the app to be ready? A: Use readiness probes on /actuator/health/readiness, with group-specific checks, an appropriate startup probe for slow starters, and server.shutdown=graceful, so rolling updates drain traffic cleanly.

Previous

Spring Boot Data, Transactions & Caching — Interview Questions

Next

Spring Boot Performance, Scaling & Resilience — Interview Questions

AI Tutor

Lesson: Spring Boot Testing, Error Pages & Deployment — Interview Questions

Quick actions

AI responses can be inaccurate. Verify critical information.