Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Testing, Swagger, Docker and Deployment for Spring Boot (Uptime Monitor Part 8)

Finish a production-ready Spring Boot project: JUnit, Mockito, WireMock and Testcontainers tests, Swagger, a multi-stage Dockerfile, CI and deployment. Part 8 of the UpCheck series.

Sumit KumarUpdated Oct 14, 20268 min readJava
Testing, Swagger, Docker and Deployment for Spring Boot (Uptime Monitor Part 8)

Part 8 of the UpCheck series proves the code works with three kinds of tests, documents the API with Swagger, packages it with Docker and deploys it to a real server.

Testing, Swagger, Docker and deployment#

Today you prove the code works with three kinds of tests, document the API with Swagger, package it as a small Docker image, and put it on a real server.

The testing strategy#

Test type Tool What it proves Speed
Unit JUnit 5 the UP/DOWN rules in Monitor milliseconds
Unit with mocks Mockito CheckService opens incidents and publishes events milliseconds
HTTP WireMock HttpChecker handles 200, 503, timeouts, refused connections ~3 s
Integration Testcontainers + MockMvc real MySQL, Flyway, JWT, ownership, validation ~20 s

Step 1: Unit test the business rule#

Java
package com.upcheck.monitor;

import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.assertj.core.api.Assertions.assertThat;

class MonitorTest {

    private static final Instant NOW = Instant.parse("2026-10-13T10:00:00Z");

    private Monitor newMonitor() {
        return new Monitor(null, "Blog", "https://example.com", 5);
    }

    @Test
    void firstSuccessfulCheckMovesUnknownToUp() {
        assertThat(newMonitor().recordCheck(true, NOW, 2)).isEqualTo(MonitorStatus.UP);
    }

    @Test
    void singleFailureDoesNotMarkDown() {
        Monitor m = newMonitor();
        m.recordCheck(true, NOW, 2);

        assertThat(m.recordCheck(false, NOW, 2)).isNull();
        assertThat(m.getStatus()).isEqualTo(MonitorStatus.UP);
        assertThat(m.getConsecutiveFailures()).isEqualTo(1);
    }

    @Test
    void reachingThresholdMarksDownOnlyOnce() {
        Monitor m = newMonitor();
        m.recordCheck(true, NOW, 2);
        m.recordCheck(false, NOW, 2);

        assertThat(m.recordCheck(false, NOW, 2)).isEqualTo(MonitorStatus.DOWN);
        assertThat(m.recordCheck(false, NOW, 2)).isNull();   // no duplicate transition
    }

    @Test
    void successAfterDownRecovers() {
        Monitor m = newMonitor();
        m.recordCheck(false, NOW, 1);

        assertThat(m.recordCheck(true, NOW, 1)).isEqualTo(MonitorStatus.UP);
        assertThat(m.getConsecutiveFailures()).isZero();
    }

    @Test
    void changingUrlSchedulesImmediateCheckButKeepsStatus() {
        Monitor m = newMonitor();
        m.recordCheck(false, NOW, 1);

        m.update("Blog", "https://new.example.com", 5, true);

        assertThat(m.getStatus()).isEqualTo(MonitorStatus.DOWN);   // open incident can still close
        assertThat(m.getLastCheckedAt()).isNull();                   // due on the next poll
        assertThat(m.getConsecutiveFailures()).isZero();
    }
}

Step 2: Mockito test for CheckService#

Java
package com.upcheck.check;

import com.upcheck.alert.MonitorStatusChangedEvent;
import com.upcheck.config.AppProperties;
import com.upcheck.incident.Incident;
import com.upcheck.incident.IncidentService;
import com.upcheck.monitor.*;
import com.upcheck.user.User;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.context.ApplicationEventPublisher;

import java.time.Duration;
import java.time.Instant;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class CheckServiceTest {

    private static final Instant T0 = Instant.parse("2026-10-13T10:00:00Z");

    @Mock MonitorRepository monitorRepository;
    @Mock CheckResultRepository checkResultRepository;
    @Mock IncidentService incidentService;
    @Mock MonitorService monitorService;
    @Mock ApplicationEventPublisher events;

    private CheckService service;
    private Monitor monitor;

    @BeforeEach
    void setUp() {
        AppProperties props = new AppProperties(
                new AppProperties.Jwt("unused", Duration.ofHours(1)),
                new AppProperties.Checker(Duration.ofSeconds(30), Duration.ofSeconds(10), 1, true, 20),
                new AppProperties.Retention(30, "0 0 0 * * *"),
                new AppProperties.Mail("test@upcheck.dev"));
        service = new CheckService(monitorRepository, checkResultRepository, incidentService,
                monitorService, events, props);
        monitor = new Monitor(new User("Asha", "asha@example.com", "hash"), "Shop", "https://shop.example", 5);
        when(monitorRepository.findById(1L)).thenReturn(Optional.of(monitor));
    }

    @Test
    void failureOpensIncidentAndPublishesDownEvent() {
        service.record(1L, CheckOutcome.httpFailure(500, 120, T0));

        assertThat(monitor.getStatus()).isEqualTo(MonitorStatus.DOWN);
        verify(incidentService).open(monitor, T0, "HTTP 500");

        ArgumentCaptor<MonitorStatusChangedEvent> captor = ArgumentCaptor.forClass(MonitorStatusChangedEvent.class);
        verify(events).publishEvent(captor.capture());
        assertThat(captor.getValue().newStatus()).isEqualTo(MonitorStatus.DOWN);
        assertThat(captor.getValue().ownerEmail()).isEqualTo("asha@example.com");
    }

    @Test
    void recoveryResolvesIncidentAndReportsDowntime() {
        monitor.recordCheck(false, T0, 1);   // already DOWN
        Incident open = new Incident(monitor, T0, "HTTP 500");
        Instant later = T0.plus(Duration.ofMinutes(12));
        when(incidentService.resolve(monitor, later)).thenAnswer(inv -> {
            open.resolve(later);
            return Optional.of(open);
        });

        service.record(1L, CheckOutcome.success(200, 90, later));

        ArgumentCaptor<MonitorStatusChangedEvent> captor = ArgumentCaptor.forClass(MonitorStatusChangedEvent.class);
        verify(events).publishEvent(captor.capture());
        assertThat(captor.getValue().newStatus()).isEqualTo(MonitorStatus.UP);
        assertThat(captor.getValue().downtime()).isEqualTo(Duration.ofMinutes(12));
    }

    @Test
    void firstSuccessSendsNoAlert() {
        service.record(1L, CheckOutcome.success(200, 80, T0));

        assertThat(monitor.getStatus()).isEqualTo(MonitorStatus.UP);
        verify(events, never()).publishEvent(any());
        verify(checkResultRepository).save(any(CheckResult.class));
    }
}

Step 3: WireMock test for HttpChecker#

WireMock starts a fake web server so you can test slow and broken sites without the internet.

Java
package com.upcheck.check;

import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import com.upcheck.config.AppProperties;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.time.Clock;
import java.time.Duration;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.assertj.core.api.Assertions.assertThat;

@WireMockTest
class HttpCheckerTest {

    private HttpChecker checker;

    @BeforeEach
    void setUp() {
        AppProperties props = new AppProperties(
                new AppProperties.Jwt("unused", Duration.ofHours(1)),
                new AppProperties.Checker(Duration.ofSeconds(30), Duration.ofSeconds(1), 2, true, 20),
                new AppProperties.Retention(30, "0 0 0 * * *"),
                new AppProperties.Mail("test@upcheck.dev"));
        checker = new HttpChecker(props, Clock.systemUTC());
    }

    @Test
    void status200IsUp(WireMockRuntimeInfo wm) {
        stubFor(get("/health").willReturn(aResponse().withStatus(200)));

        CheckOutcome outcome = checker.check(wm.getHttpBaseUrl() + "/health");

        assertThat(outcome.up()).isTrue();
        assertThat(outcome.statusCode()).isEqualTo(200);
        assertThat(outcome.responseTimeMs()).isNotNull();
    }

    @Test
    void status503IsDown(WireMockRuntimeInfo wm) {
        stubFor(get("/").willReturn(aResponse().withStatus(503)));

        CheckOutcome outcome = checker.check(wm.getHttpBaseUrl() + "/");

        assertThat(outcome.up()).isFalse();
        assertThat(outcome.errorMessage()).isEqualTo("HTTP 503");
    }

    @Test
    void slowResponseTimesOut(WireMockRuntimeInfo wm) {
        stubFor(get("/slow").willReturn(aResponse().withStatus(200).withFixedDelay(3_000)));

        CheckOutcome outcome = checker.check(wm.getHttpBaseUrl() + "/slow");

        assertThat(outcome.up()).isFalse();
        assertThat(outcome.errorMessage()).contains("timed out");
    }

    @Test
    void unreachableHostIsDown() {
        CheckOutcome outcome = checker.check("http://localhost:1/");   // nothing listens on port 1

        assertThat(outcome.up()).isFalse();
        assertThat(outcome.errorMessage()).isNotBlank();
    }
}

Step 4: Integration test with a real MySQL (Testcontainers)#

@ServiceConnection (Spring Boot 3.1+) wires the container's URL, user and password into the datasource automatically. Docker must be running.

YAML
# src/test/resources/application-test.yml
upcheck:
  jwt:
    secret: dGVzdC1vbmx5LXNlY3JldC1rZXktZm9yLXVwY2hlY2staW50ZWdyYXRpb24tdGVzdHM=
  checker:
    poll-interval: PT1H        # keep the scheduler quiet during tests
    allow-private-hosts: true

spring:
  mail:
    host: localhost
    port: 2525
Java
package com.upcheck;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.testcontainers.containers.MySQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Testcontainers
class MonitorApiIntegrationTest {

    @Container
    @ServiceConnection
    static MySQLContainer<?> mysql = new MySQLContainer<>("mysql:8.4");

    @Autowired MockMvc mvc;
    @Autowired ObjectMapper mapper;

    @Test
    void userCanRegisterCreateAndListMonitors() throws Exception {
        String token = registerAndGetToken("dev@example.com");

        mvc.perform(post("/api/monitors")
                        .header("Authorization", "Bearer " + token)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                {"name":"Example","url":"https://example.com","intervalMinutes":5}
                                """))
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.status").value("UNKNOWN"));

        mvc.perform(get("/api/monitors").header("Authorization", "Bearer " + token))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.totalElements").value(1));
    }

    @Test
    void usersCannotSeeEachOthersMonitors() throws Exception {
        String alice = registerAndGetToken("alice@example.com");
        String bob = registerAndGetToken("bob@example.com");

        String body = mvc.perform(post("/api/monitors")
                        .header("Authorization", "Bearer " + alice)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                {"name":"Alice site","url":"https://example.org","intervalMinutes":1}
                                """))
                .andReturn().getResponse().getContentAsString();
        long id = mapper.readTree(body).get("id").asLong();

        mvc.perform(get("/api/monitors/" + id).header("Authorization", "Bearer " + bob))
                .andExpect(status().isNotFound());
    }

    @Test
    void invalidIntervalIsRejected() throws Exception {
        String token = registerAndGetToken("val@example.com");

        mvc.perform(post("/api/monitors")
                        .header("Authorization", "Bearer " + token)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                {"name":"Bad","url":"https://example.com","intervalMinutes":7}
                                """))
                .andExpect(status().isBadRequest())
                .andExpect(jsonPath("$.errors.intervalAllowed").exists());
    }

    @Test
    void requestWithoutTokenGets401() throws Exception {
        mvc.perform(get("/api/monitors")).andExpect(status().isUnauthorized());
    }

    private String registerAndGetToken(String email) throws Exception {
        String response = mvc.perform(post("/api/auth/register")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                {"name":"Dev","email":"%s","password":"Str0ngPass!"}
                                """.formatted(email)))
                .andExpect(status().isCreated())
                .andReturn().getResponse().getContentAsString();
        return mapper.readTree(response).get("accessToken").asText();
    }
}

Run everything with ./mvnw verify.

Step 5: Swagger UI with JWT support#

Java
package com.upcheck.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI upCheckOpenApi() {
        String scheme = "bearerAuth";
        return new OpenAPI()
                .info(new Info()
                        .title("UpCheck API")
                        .version("1.0.0")
                        .description("Website uptime monitoring with Spring Boot and MySQL"))
                .addSecurityItem(new SecurityRequirement().addList(scheme))
                .components(new Components().addSecuritySchemes(scheme,
                        new SecurityScheme()
                                .type(SecurityScheme.Type.HTTP)
                                .scheme("bearer")
                                .bearerFormat("JWT")));
    }
}

Open http://localhost:8080/swagger-ui.html, log in through /api/auth/login, click Authorize, paste the token, and try every endpoint from the browser. In production Swagger is off unless SWAGGER_ENABLED=true.

Step 6: A small, secure Docker image#

A multi-stage build compiles with Maven, then copies only the jar into a slim JRE image. The app runs as a non-root user, and Docker restarts it if the health check fails.

DOCKERFILE
# ---- Stage 1: build the jar ----
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /app
COPY pom.xml .
RUN mvn -q dependency:go-offline          # cached layer: re-runs only when pom.xml changes
COPY src ./src
RUN mvn -q package -DskipTests

# ---- Stage 2: small runtime image ----
FROM eclipse-temurin:21-jre-alpine
WORKDIR /app
RUN addgroup -S upcheck && adduser -S upcheck -G upcheck
COPY --from=build /app/target/upcheck-*.jar app.jar
USER upcheck

ENV SPRING_PROFILES_ACTIVE=prod
ENV JAVA_OPTS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
  CMD wget -qO- http://localhost:8080/actuator/health/liveness || exit 1

ENTRYPOINT ["sh", "-c", "exec java $JAVA_OPTS -jar app.jar"]
Bash
# .env.example  (copy to .env on the server, never commit it)
SPRING_PROFILES_ACTIVE=prod
DB_URL=jdbc:mysql://your-db-host:3306/upcheck?serverTimezone=UTC&useSSL=true
DB_USERNAME=upcheck
DB_PASSWORD=change-me
JWT_SECRET=            # openssl rand -base64 48
MAIL_HOST=smtp.your-provider.com
MAIL_PORT=587
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_FROM=alerts@yourdomain.com
SWAGGER_ENABLED=false

Step 7: CI with GitHub Actions#

Every push runs all tests (GitHub runners have Docker, so Testcontainers works) and builds the image.

YAML
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21
          cache: maven
      - name: Build and test
        run: mvn -B verify
      - name: Build Docker image
        run: docker build -t upcheck:${{ github.sha }} .

Step 8: Deploy to a Linux server#

Any small VPS with 1 GB RAM works (AWS Lightsail, DigitalOcean, Hetzner). Use a managed MySQL or run MySQL in Docker on the same machine.

Bash
# on the server
git clone https://github.com/<you>/upcheck.git && cd upcheck
cp .env.example .env && nano .env        # fill in real values

docker build -t upcheck .
docker run -d --name upcheck --restart unless-stopped \
  --env-file .env -p 8080:8080 upcheck

curl localhost:8080/actuator/health      # {"status":"UP"}

Put Nginx or Caddy in front for HTTPS (Caddy gets a free Let's Encrypt certificate automatically). For email in production, use a transactional provider such as Brevo, Amazon SES or Resend through their SMTP settings.

Production checklist#

  • JWT_SECRET is random, at least 256 bits, and only in environment variables
  • Database user has rights only on the upcheck schema
  • HTTPS in front of the app; port 8080 not open to the internet
  • allow-private-hosts: false in production (SSRF protection)
  • Swagger disabled or protected in production
  • Daily MySQL backups (mysqldump or your provider's snapshots)
  • ShedLock added before running more than one instance
  • Add UpCheck's own /actuator/health to a second, independent monitor

FAQ#

Is this Spring Boot project good for a fresher's resume?#

Yes. It shows REST design, JPA with MySQL, Flyway, JWT security, background scheduling, concurrency with virtual threads, events, SQL aggregates, testing with Testcontainers, and Docker. Deploy it and put the live Swagger link on your resume.

Why use virtual threads for the checker?#

Each check mostly waits on the network. Virtual threads make waiting almost free, so 500 parallel checks need no thread-pool tuning. Platform threads would need a big pool and much more memory.

Can I use PostgreSQL instead of MySQL?#

Yes, with two changes: swap the driver and flyway-mysql for postgresql and flyway-database-postgresql, and rewrite the two native queries (TIMESTAMPADD and DELETE ... LIMIT are MySQL syntax).

Why not use @Scheduled with a fixed rate per monitor?#

Thousands of monitors would mean thousands of timers that are lost on restart. A single poller that asks the database "who is due?" survives restarts and scales with an index.

How do I run UpCheck on two servers?#

Add ShedLock so only one instance runs runDueChecks at a time. Everything else is already stateless.

How do I add Slack or Telegram alerts?#

Add another @TransactionalEventListener for MonitorStatusChangedEvent that posts to a webhook. The checker does not change at all, which is the point of using events.

What you built, and what to add next#

In 8 days you built a deployable uptime monitor with JWT auth, a concurrent background checker, incident tracking, email alerts, SQL-powered stats, and tests at every level. Good next features for version 2:

  • A public status page per user (GET /status/{slug}, no login)
  • SSL certificate expiry warnings
  • Keyword checks (page must contain a given text)
  • Slack, Discord and Telegram webhooks
  • A React or Angular dashboard with response-time charts
  • Refresh tokens and email verification

If you build along, share your deployed link in the comments. Happy coding!

Key takeaways#

  • Unit-test business rules, mock collaborators with Mockito, and fake websites with WireMock.
  • Testcontainers runs integration tests against a real MySQL with zero setup.
  • A multi-stage Dockerfile, CI on every push and a production checklist make it deploy-ready.