Spring BootJava 21Spring Framework深入淺出

Spring Boot 06: what tests prove, from debugging to JAR and WAR

···5 min read
Back to the Spring Boot learning pathContinue with the independent JBoss EAP series: foundations and practical work

What should you trust more after mvn test passes? “The entire system works” is too broad. Read the assertions to identify their scope, then ask what remains unverified when startup or deployment changes.

Version note: this series is based on Spring Boot 3.5.16 because it targets JBoss EAP 8.1. Spring now offers the newer 4.1. For differences between 3.5 and 4.0, see the Spring Boot 4.0 Migration Guide in the sources.

Identify the environment created by the test

java
@SpringBootTest(properties = {
    "spring.datasource.url=jdbc:h2:mem:bootlab-test;DB_CLOSE_DELAY=-1",
    "lab.label=test-label"
})
@AutoConfigureMockMvc
class LabIntegrationTest {
    // See the download for injected fields and complete tests.
}

@SpringBootTest loads the application context. MockMvc exercises MVC handling inside the process without establishing a real TCP listener. This lab uses its real service and H2 JDBC rather than mocking the entire chain, so it observes writes but does not verify EAP, DB2, or MQ integration.

The Spring Boot 3.5 testing page states: “By default, @SpringBootTest does not start the server but instead sets up a mock environment for testing web endpoints.” The webEnvironment attribute decides whether a real port opens. It has four values.

ValueDocumented behaviorThis lab
MOCK (default)Loads a web context with a mock web environment; no embedded server startsUsed, with @AutoConfigureMockMvc
RANDOM_PORTStarts the embedded server on a random portNot used; switch only to test real TCP
DEFINED_PORTStarts the embedded server on the configured port, or 8080Not used
NONELoads a context through SpringApplication with no web environmentNot used
@SpringBootTest webEnvironment (summarized from the Spring Boot 3.5 testing docs)

If a test class is @Transactional, the docs say each test method rolls back by default. RANDOM_PORT and DEFINED_PORT differ: the HTTP client and server run in separate threads and transactions. The sentence is: “Any transaction initiated on the server does not roll back in this case.” Lesson 05 omits @Transactional on its tests to observe the service’s own commit and rollback.

ApproachUseful evidenceNot established
Plain unit testFunction or class rulesSpring wiring and transaction advice
MVC slice such as @WebMvcTestMappings, conversion, validationReal DB or whole context
This context + MockMvc + H2Specified HTTP and database effectsReal TCP, DB2, EAP, MQ
Packaged JAR + real HTTPPackaging, startup, embedded server responsesExternal-container modules and corporate connections
Same cases on target environmentsActual integration and old/new behaviorUntested cases and production traffic
Match test boundaries to the question

Read assertions, not only test names

java
mvc.perform(post("/api/tickets")
        .contentType("application/json")
        .content("{\"title\":\" \"}"))
    .andExpect(status().isBadRequest())
    .andExpect(jsonPath("$.code").value("INVALID_REQUEST"));
assertThat(count()).isZero();

This excerpt checks the blank-title response and the absence of writes. A rejected response alone would miss accidental persistence. The successful-create test separately checks 201, Location, the returned id, and a follow-up read. Dynamic ids are checked through relationships rather than compared to a fixed value.

The Boot 3.5 docs list MockMvcTester as one integration; it “wraps MockMvc and uses AssertJ.” This lab uses the original MockMvc perform and andExpect style. Both test the same layer; only the assertion style differs.

The lab includes eight integration tests; its VALIDATION.md records execution evidence. A test count is not a coverage percentage or a guarantee for all inputs. Date, permission, or retry changes require corresponding cases rather than relying on the existing eight.

Fix the case and artifact before debugging

Record the input, settings, artifact, response, and data result. Find the earliest boundary that differs from expectations. For startup exceptions, inspect the relevant nested cause rather than treating “context failed” as the diagnosis. Change one cause and repeat the same case to connect the fix to the outcome.

bash
mvn test
mvn package
java -jar target/boot-learning-lab-1.0.0.jar --server.port=8081
# Another terminal:
curl -i http://127.0.0.1:8081/api/ping

JAR and WAR change some runtime responsibilities

This project packages an executable JAR whose main starts an embedded server. A traditional WAR is loaded by an external Servlet container; Boot’s documented setup includes a SpringBootServletInitializer subclass, WAR packaging, and provided container dependencies. Renaming the file is insufficient. The download ships the JAR only. The WAR build and embedded-Tomcat start are covered in EAP lesson 08, with its own sample. Deployment to EAP itself is not tested in either series.

Lesson 08: build and inspect a Spring Boot WAR
Left: an executable JAR. java -jar starts main, SpringApplication.run builds the context, embedded Tomcat opens the port, and server.port applies. Right: a WAR on EAP. EAP starts first and owns the listener; after deployment, configure on your SpringBootServletInitializer subclass builds the context; requests enter through the EAP listener and context root, and server.port does not change it. Footer: a WAR built by the Boot plugin can still run with java -jar; provided dependencies go to lib-provided
JAR versus WAR changes who starts the app and who owns the port. The three steps and lib-provided come from the Spring Boot 3.5 traditional deployment docs. Diagram drawn by KeepOnFirst.

With Boot’s build plugins, a WAR has one more detail. The traditional deployment page says that marking the embedded server dependency as provided produces an executable WAR. Provided dependencies go into a lib-provided directory. It can deploy to a container and also start with java -jar. The Maven plugin docs describe repackage this way: “Repackage existing JAR and WAR archives so that they can be executed from the command line using java -jar.”

This creates a reading trap. A WAR that starts with java -jar proves only the embedded-server path. It does not prove that EAP can load it. For Gradle projects, the docs prefer providedRuntime to compileOnly. One of the reasons: compileOnly dependencies are not on the test classpath, so web integration tests fail.

On EAP, check the listener and context root, then data source/JNDI, transaction manager, logging, and loaded libraries. server.port does not reconfigure EAP’s listener. Boot 3.5’s Servlet requirement is only one condition; vendor support and application modules require separate checks.

Exercise: write a handoff you can explain

Suppose lab.max-title-length changes from 80 to 100. Predict which test fails and whether the table can still store the value. Write the behavior change, configuration location, test adjustment, and remaining integration limits—not just “configuration updated, tests passed.”

Answer: change the 81-character case without removing its purpose

The old 81-character rejection should become acceptance. Check the new boundary at 100 and 101, retaining the no-write assertion on failure. The table’s 200 limit is not reached, but a legacy contract capped at 80 would still change. The learning objective is connecting intent, code, and evidence.

Next-stage EAP/JBoss context: review the migration responsibility mapDownload the complete ticket API lab (ZIP)

Sources