Muhammad Fari Madyan
Hire me
Spring Boot · part 8 of 8

Java Spring Boot + React E-Learning Part 8: Architecture Docs That Match the Code — Testing Strategy & JaCoCo in CI

Closing the series: correcting README claims that no longer matched the code, writing docs/ARCHITECTURE.md with Mermaid diagrams, design decisions and honest scaling limits (PR #24), and the testing strategy behind PR #25: 55 fast backend tests, mocks at the right boundaries, and a JaCoCo coverage summary on every GitHub Actions run.

Muhammad Fari Madyan

· 12 min read

Baca dalam Bahasa Indonesia →

Introduction: When the README Stops Telling the Truth

After Part 5, Part 6 and Part 7, the code of mfarim/spring-elearning-react had changed a lot. My README, on the other hand, had barely changed. It still promised a "Redis cache", a STOMP broker "backed by Redis", and a "decoupled micro-architecture".

None of that was true. Redis held refresh tokens, the broker was Spring's in-memory simple broker, and the backend was a single Spring Boot service. I had even repeated the same "Redis cache" claim myself in Part 1 of this series.

The way I see it, inaccurate docs cost more than missing docs. A contributor plans work around a cache that doesn't exist. An interviewer asks how cache invalidation works, and the honest answer is "there is no cache". An operator scales out because "STOMP uses Redis", and teachers stop receiving live events.

In this final part I'll walk you through two pull requests:

Docs and tests map

Click the diagram to open it at full size.


1. Auditing the README Against the Code

I went through the README one claim at a time and checked each one against the source, the same way I audited the security code in Part 5:

README saidThe code actually doesFixed text
"Redis cache"No @Cacheable, no cache manager. Redis stores refresh-token jtis"Redis-backed refresh-token rotation"
"STOMP message broker backed by Redis"config.enableSimpleBroker("/topic", "/queue"), in memory"in-memory simple broker" (Redis fan-out came later in PR #25, as an opt-in)
"decoupled micro-architecture"One Spring Boot deployable with domain packages"modular monolith with a separate React SPA"
Redis as "Session & Telemetry Broker"Sessions are stateless JWTs; telemetry goes through STOMP"Refresh-token store, rotation & revocation by jti"
Node 20 AlpineDockerfile uses node:22-alpine (since PR #6)Node 22, Nginx 1.28
Project tree with learning/ module and config/ holding JWTPackages are material/, announcement/, grade/, and a separate security/Tree regenerated from the real packages

The fix was not to make the system sound smaller. It was to describe what it actually does, and to point to one place that explains why.

Rule I now follow: every architecture claim in a README should be checkable with a grep. If "Redis cache" is written down, @Cacheable or a CacheManager must exist somewhere.


2. What Goes Into docs/ARCHITECTURE.md

The README answers "what is this and how do I run it". docs/ARCHITECTURE.md answers "how is it built, why, and where does it break". I split it into ten sections:

#SectionFormatQuestion it answers
1System contextMermaid flowchart + tableWhat runs where, and who talks to whom?
2Backend modulesTableWhere does a piece of logic belong?
3Data modelMermaid erDiagramHow are classes, exams, attempts and answers related?
4Authentication and token rotationMermaid sequenceDiagramWhat happens on login, refresh, reuse, logout?
5Exam lifecyclesequenceDiagram + stateDiagram-v2Which rules does the server enforce during an exam?
6Real-time proctoringRules + delivery modesWho may subscribe, and how do events reach the teacher?
7Design decisionsDecision / alternatives / whyWhy this and not the obvious alternative?
8Scaling limits and roadmapSettings table + open itemsWhat changes with several instances, and what is still missing?
9Testing strategyCurrent vs plannedWhat is tested, at which level?
10OperationsListCI, deploy, health checks, background jobs, logs

Diagrams as code

I drew every diagram in Mermaid, so GitHub renders them and they live next to the code in the same pull request. When a flow changes, the diagram changes in the same diff, and the reviewer sees both. Here's the system context today:

Decisions, with the alternatives you rejected

The most useful section for readers (and for me six months from now) is the decision table. Each row names the alternative I considered and why it lost:

DecisionAlternatives consideredWhy
Modular monolithMicroservicesOne team and one deployable; domain packages keep boundaries clear and allow later extraction
Stateless JWT + refresh tokens in RedisServer-side sessions; JWT without a storeStateless hot path, while logout, rotation and revoke-all still work
Refresh token in an httpOnly cookieRefresh token in localStorageNot readable by injected scripts; scoped to auth endpoints with SameSite=Strict
In-memory STOMP + Redis pub/sub fan-outSTOMP broker relay (RabbitMQ / ActiveMQ)Reuses Redis; no new broker to run
Background expiry job + optimistic lockingFinalize only when the student returnsResults on time; @Version keeps it safe across instances without a distributed lock
Server-side timing and gradingTrusting the client timer and answersThe client is untrusted
Docker Compose on a VPS behind CloudflareKubernetes; managed PaaSLow, predictable cost

A decision without its alternative reads like a preference. With the alternative, it reads like a trade-off someone actually thought about.

Writing down the limits

I deliberately opened the scaling section with an uncomfortable sentence: the default configuration targets one backend instance. After that it lists what to switch for several instances (the three settings from Part 7) and what is still open:

  • LocalDateTime with the server time zone; Instant / timestamptz in UTC would remove ambiguity across regions.
  • The access token lives in localStorage for 15 minutes; an in-memory token with silent refresh would close that gap.
  • Integration tests with Testcontainers for the full login and exam flow, and a frontend test suite.
  • A later migration to Spring Boot 4.

Listing known limits felt risky in a portfolio project. In practice it shows the opposite of what I feared: that I know where the edges are.


3. The Testing Strategy

Before PR #25, my backend had three test classes: a context-load test, JwtProviderTest, and FileStorageServiceTest. Every rule I added in Parts 6 and 7 came with tests. The suite now has 55 tests in 12 classes:

ClassTestsWhat it protects
AnswerGraderTest6Short-answer normalization, `
ExamRunnerServiceTest10Scoring, manual grading, deadlines, retries, expiry job
ExamRealtimeServiceTest5After-commit delivery, Redis fan-out, fallback, malformed messages
RefreshTokenStoreTest4Store, consume exactly once, wrong user, revoke-all
RefreshTokenCookiesTest4Cookie attributes, clearing, body-to-cookie move
JwtProviderTest7typ claim both ways, unique jti, known secret refused
InMemoryRateLimiterTest3Capacity, separate keys, reset
RedisRateLimiterTest4Shared counter, rejection, fail open, reset
S3StorageBackendTest3Upload, download metadata, missing object
FileStorageServiceKeyTest2Random names, absolute/backslash keys rejected
FileStorageServiceTest6Path traversal, dangerous extensions
BackendApplicationTests1Spring context starts against PostgreSQL and Redis

Mock at the boundary, test the rule

54 of the 55 tests are plain JUnit 5 + Mockito, with no Spring context, and they run in seconds. The idea is simple: mock the infrastructure (Redis, the S3 client, JPA repositories) and test the rule for real.

For RefreshTokenStore, the rule is "a refresh token works exactly once". The test stubs Redis to behave like GETDEL (a value the first time, null after that) and checks the store's answer:

JAVA
@Test
void aRefreshTokenCanBeConsumedExactlyOnce() {
    when(values.getAndDelete("auth:refresh:jti-1")).thenReturn("7").thenReturn(null);

    assertTrue(store.consume("jti-1", 7L));
    assertFalse(store.consume("jti-1", 7L), "a replayed refresh token must be rejected");
}

The fail-open decision from Part 7 is a rule too, so I gave it a test instead of a comment:

JAVA
@Test
void failsOpenWhenRedisIsUnavailable() {
    when(redis.execute(eq(RedisRateLimiter.INCREMENT_SCRIPT), eq(List.of("rate:login:ip:1")), eq("60000")))
            .thenThrow(new RedisConnectionFailureException("connection refused"));

    assertTrue(limiter.tryAcquire("login:ip:1", 5, minute));
}

Testing "only after commit" without a database

The trickiest rule to test was "monitor events are sent only after the transaction commits". It turns out I didn't need a real transaction. Spring's TransactionSynchronizationManager can be driven by hand:

JAVA
@Test
void insideATransactionTheEventIsSentOnlyAfterCommit() {
    TransactionSynchronizationManager.initSynchronization();

    service("local").broadcastExamEvent(7L, "EXAM_SUBMITTED", Map.of("score", 80));
    verifyNoInteractions(messaging);                 // nothing sent yet

    TransactionSynchronizationManager.getSynchronizations().forEach(TransactionSynchronization::afterCommit);
    verify(messaging).convertAndSend(eq(MONITOR), any(Object.class));
}

An @AfterEach clears the synchronization so tests don't leak state into each other.

Pure code needs no mocks at all

AnswerGrader from Part 6 has no dependencies, so its tests are just inputs and outputs. That was my main reason for pulling grading out of the service: the rules that decide a student's score should be the easiest code in the project to test.

Testing the bug, not just the feature

The tests I value most are the ones that reproduce the bugs from Part 6, so those bugs can't come back unnoticed:

JAVA
@Test void savingAnAnswerAfterTheDeadlineFinalizesTheAttempt()          // the rollback bug
@Test void manualGradingKeepsAttemptPendingUntilEveryEssayIsGraded()  // partial grading shown as final
@Test void startCreatesTheNextAttemptNumberWhenRetriesAreAllowed()     // the retake crash
@Test void finalizeDoesNothingForAttemptsThatAreAlreadyFinished()      // double grading

What the unit tests can't prove

Mocks can't prove that the native SQL in findExpiredInProgressAttemptIds runs on PostgreSQL, that @Version really produces a conflict, or that the V3 migration applies cleanly to old data. For that I need a real database. The one integration test (contextLoads) runs against PostgreSQL 16 and Redis 7 service containers in CI, so Flyway applies V1 → V3 on every build, but a full flow test with Testcontainers is still on the roadmap. The docs say so.


4. JaCoCo Coverage on Every CI Run

I measure coverage with the JaCoCo Maven plugin. prepare-agent instruments the tests, and report runs in the test phase:

XML
<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>${jacoco.version}</version> <!-- 0.8.12 -->
    <executions>
        <execution>
            <id>prepare-agent</id>
            <goals><goal>prepare-agent</goal></goals>
        </execution>
        <execution>
            <id>report</id>
            <phase>test</phase>
            <goals><goal>report</goal></goals>
        </execution>
    </executions>
</plugin>

The GitHub Actions workflow starts PostgreSQL and Redis as service containers, runs ./mvnw clean package, then turns jacoco.csv into a one-line summary on the job page and uploads the HTML report:

YAML
- name: Build and Package with Maven
  run: ./mvnw clean package

- name: Publish coverage summary
  if: always()
  run: |
    if [ -f target/site/jacoco/jacoco.csv ]; then
      awk -F, 'NR > 1 { missed += $8; covered += $9 }
        END { total = missed + covered; if (total > 0) printf "### Backend line coverage: %.1f%% (%d of %d lines)\n", 100 * covered / total, covered, total }' \
        target/site/jacoco/jacoco.csv >> "$GITHUB_STEP_SUMMARY"
    fi

- name: Upload coverage report
  if: always()
  uses: actions/upload-artifact@v4
  with:
    name: jacoco-report
    path: backend/target/site/jacoco
    if-no-files-found: ignore

Columns 8 and 9 of the JaCoCo CSV are LINE_MISSED and LINE_COVERED. if: always() publishes the numbers even when a test fails, which is exactly when you want to look.

Why there is no coverage threshold yet

JaCoCo can fail the build below a percentage. For now, I chose not to use that. Controllers and the Excel import code are still mostly untested, so any threshold today would either be meaninglessly low or block unrelated pull requests. My plan, written in the testing strategy table, is to add the threshold once the Testcontainers suite exists. Until then, the number is visible on every run, and a drop gets noticed in review.


5. The Whole Series in One Table

PartTopicPull requests
1Rebuilding the Laravel monolith as Spring Boot + React—
2Path traversal, refresh tokens, Docker resilience#1
3Stateless JWT, method-level RBAC, OWASP Top 10, rate limiting#1, #3, #4
4Single VPS deployment with Docker Compose, Nginx and SSL#2
5Second audit: real client IP, refresh rotation, forced password change, file and STOMP authorization#5, #6
6Exam integrity: noRollbackFor, expiry job, unique attempts, @Version#25
7httpOnly cookie, CSP, Redis and S3 for several instances#25
8Architecture docs, testing strategy, JaCoCo#24, #25

Conclusion

This series started as "rebuild a Laravel e-learning platform with Spring Boot and React". It ended up somewhere more useful: a system whose security, exam rules and scaling limits are written down, tested, and match the code.

If I had to keep just three habits from these eight parts, they'd be these:

  1. Audit with the attacker's knowledge. Assume they've already read your repo (Part 5).
  2. Let the database guarantee what if statements can't. Unique keys, version columns and transaction boundaries (Part 6).
  3. Make docs checkable. Every claim should be one grep away from the code that proves it (Part 8).

Thanks for following along all the way to the end. The code, the docs and the live demo are all public, so I'd love to see your issues and pull requests.

ShareLinkedInXWhatsApp

Written by Muhammad Fari Madyan

Senior Full Stack Engineer and co-founder of LampungDev. I write up what I build so others can learn from it.

Work with me
← part 7httpOnly Refresh Cookie, CSP & Multi-Instance Scaling with Redis and S3series completeBack to all articles →

Muhammad Fari Madyan

Senior Full Stack Engineer building web and mobile systems that hold up in production. Co-founder of LampungDev. Based in Bandar Lampung, Indonesia (UTC+7), working remote.

Work

Case studiesCahTixExam platform, 4 stacksOpen source

© 2026 Muhammad Fari Madyan

Designed and built by Muhammad Fari Madyan