A minimal Spring Boot example project demonstrating how to test REST API controllers in Java using MockMvc, @SpringBootTest, @AutoConfigureMockMvc, JUnit 5, and Gradle.
Note: The original legacy version (Java 8 / Spring Boot 2.3.0 / Gradle 6.3) is archived under release
v0.1.0-legacy.
- Component-oriented REST API: Separate controllers (
GetAllandGetOne) under/api/v1/articlesreturningArticledomain models with UUID identifiers. - MockMvc controller testing: Verifies HTTP status codes and JSON payloads using
MockMvcRequestBuildersandMockMvcResultMatchers(status()andjsonPath()). - Application context verification: Includes a baseline
@SpringBootTestcheck (ApplicationTests) confirming the Spring application context loads cleanly. - Gradle Wrapper support: Self-contained Gradle 8.11.1 wrapper configured with
useJUnitPlatform()for consistent test execution across environments.
- Language: Java 17 (Gradle Java toolchain)
- Framework: Spring Boot
3.4.13(spring-boot-starter-web) - Testing:
spring-boot-starter-test, JUnit 5 (JUnit Jupiter / JUnit Platform), SpringMockMvc, JsonPath - Build Tool: Gradle 8.11.1 (with Gradle Wrapper)
spring-boot-unit-test/
├── build.gradle
├── settings.gradle
├── gradlew / gradlew.bat
└── src/
├── main/
│ ├── java/com/example/demo/
│ │ ├── Application.java
│ │ └── components/article/
│ │ ├── api/
│ │ │ ├── GetAll.java # GET /api/v1/articles
│ │ │ └── GetOne.java # GET /api/v1/articles/{id}
│ │ └── domain/
│ │ └── Article.java # Article domain model (UUID id, title)
│ └── resources/
│ └── application.properties
└── test/
└── java/com/example/demo/
├── ApplicationTests.java # Spring context load test
└── components/article/
├── GetAllTest.java # MockMvc test for GET /api/v1/articles
└── GetOneTest.java # MockMvc test for GET /api/v1/articles/{id}
| Method | Endpoint | Controller | Description |
|---|---|---|---|
GET |
/api/v1/articles |
GetAll |
Returns a list of 5 sample Article objects (Article 001–Article 005). |
GET |
/api/v1/articles/{id} |
GetOne |
Returns a single Article with title "article of id {id}". |
- JDK 17+ (or a JDK version compatible with Gradle 8.11.1)
git clone https://github.com/sinhsac/spring-boot-unit-test.git
cd spring-boot-unit-testOn Linux / macOS:
./gradlew testOn Windows:
gradlew.bat testOn Linux / macOS:
./gradlew bootRunOn Windows:
gradlew.bat bootRunOnce running on the default Spring Boot port (8080), you can query the endpoints:
curl http://localhost:8080/api/v1/articles
curl http://localhost:8080/api/v1/articles/id001This project is licensed under the MIT License — see the LICENSE file for details.