org.springframework.http.RequestEntity<T> extends HttpEntity and adds additional information of HTTP method and uri to the request.
org.springframework.http.ResponseEntity<T> also extends HttpEntity, where we can add additional HttpStatus (see also @ResponseStatus) to the response.
In this example we are going to show the use of RequestEntity and RequestResponse with JUnit tests.
Example
Handling request having String body
package com.logicbig.example;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
@Controller
@RequestMapping
public class MyController {
@PostMapping("test")
public ResponseEntity<String> handleRequest(RequestEntity<String> requestEntity) {
System.out.println("request body : " + requestEntity.getBody());
HttpHeaders headers = requestEntity.getHeaders();
System.out.println("request headers : " + headers);
HttpMethod method = requestEntity.getMethod();
System.out.println("request method : " + method);
System.out.println("request url: " + requestEntity.getUrl());
ResponseEntity<String> responseEntity = new ResponseEntity<>(
"my response body",
headers,
HttpStatus.OK);
return responseEntity;
}
.............
}
Integration Test
package com.logicbig.example;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
@Test
public void testController() throws Exception {
this.mockMvc.perform(post("/test")
.header("testHeader",
"xyz")
.content("test body"))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(header().string("testHeader",
"xyz"))
.andExpect(content().string(
"my response body"));
}
.............
}
mvn clean test -Dtest="ControllerTest#testController" Output$ mvn clean test -Dtest="ControllerTest#testController" [INFO] Scanning for projects... [INFO] [INFO] --------< com.logicbig.example:spring-request-response-entity >--------- [INFO] Building spring-request-response-entity 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- clean:3.2.0:clean (default-clean) @ spring-request-response-entity --- [INFO] Deleting D:\example-projects\spring-mvc\spring-request-response-entity\target [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-request-response-entity --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-request-response-entity\src\main\resources [INFO] [INFO] --- compiler:3.15.0:compile (default-compile) @ spring-request-response-entity --- [INFO] Recompiling the module because of changed source code. [INFO] Compiling 3 source files with javac [debug target 25] to target\classes [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-request-response-entity --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-request-response-entity\src\test\resources [INFO] [INFO] --- compiler:3.15.0:testCompile (default-testCompile) @ spring-request-response-entity --- [INFO] Recompiling the module because of changed dependency. [INFO] Compiling 1 source file with javac [debug target 25] to target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-request-response-entity --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.ControllerTest request body : test body request headers : [testHeader:"xyz", Content-Length:"9"] request method : POST request url: http://localhost/test [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.821 s -- in com.logicbig.example.ControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.053 s [INFO] Finished at: 2026-07-27T16:10:00+08:00 [INFO] ------------------------------------------------------------------------ INFO: Completed initialization in 2 ms
Using Backing/Command Object
package com.logicbig.example;
public class User {
private String name;
private String emailAddress;
.............
}
The Controller
package com.logicbig.example;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Arrays;
@Controller
@RequestMapping
public class MyController {
.............
@PostMapping("/user")
public ResponseEntity<String> handleUserRequest(RequestEntity<User> requestEntity) {
User user = requestEntity.getBody();
System.out.println("request body: " + user);
System.out.println("request headers " + requestEntity.getHeaders());
System.out.println("request method : " + requestEntity.getMethod());
HttpHeaders headers = new HttpHeaders();
headers.put("Cache-Control", Arrays.asList("max-age=3600"));
ResponseEntity<String> responseEntity = new ResponseEntity<>(
"my response body 2",
headers,
HttpStatus.OK);
return responseEntity;
}
}
Integration Test
package com.logicbig.example;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = MyWebConfig.class)
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@BeforeEach
public void setup() {
DefaultMockMvcBuilder builder = MockMvcBuilders.webAppContextSetup(this.wac);
this.mockMvc = builder.build();
}
.............
@Test
public void testUserController() throws Exception {
this.mockMvc.perform(post("/user")
.header("testHeader",
"headerValue")
.contentType(MediaType.APPLICATION_JSON)
.content(createUserInJson("joe",
"joe@example.com")))
.andExpect(MockMvcResultMatchers.status()
.isOk())
.andExpect(header().string("Cache-Control",
"max-age=3600"))
.andExpect(content().string(
"my response body 2"));
}
private static String createUserInJson(String name,
String email) {
return "{ \"name\": \"" + name + "\", " +
"\"emailAddress\":\"" + email + "\"}";
}
}
mvn clean test -Dtest="ControllerTest#testUserController" Output$ mvn clean test -Dtest="ControllerTest#testUserController" [INFO] Scanning for projects... [INFO] [INFO] --------< com.logicbig.example:spring-request-response-entity >--------- [INFO] Building spring-request-response-entity 1.0-SNAPSHOT [INFO] from pom.xml [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- clean:3.2.0:clean (default-clean) @ spring-request-response-entity --- [INFO] Deleting D:\example-projects\spring-mvc\spring-request-response-entity\target [INFO] [INFO] --- resources:3.3.1:resources (default-resources) @ spring-request-response-entity --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-request-response-entity\src\main\resources [INFO] [INFO] --- compiler:3.15.0:compile (default-compile) @ spring-request-response-entity --- [INFO] Recompiling the module because of changed source code. [INFO] Compiling 3 source files with javac [debug target 25] to target\classes [INFO] [INFO] --- resources:3.3.1:testResources (default-testResources) @ spring-request-response-entity --- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] skip non existing resourceDirectory D:\example-projects\spring-mvc\spring-request-response-entity\src\test\resources [INFO] [INFO] --- compiler:3.15.0:testCompile (default-testCompile) @ spring-request-response-entity --- [INFO] Recompiling the module because of changed dependency. [INFO] Compiling 1 source file with javac [debug target 25] to target\test-classes [INFO] [INFO] --- surefire:3.2.5:test (default-test) @ spring-request-response-entity --- [INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider [WARNING] file.encoding cannot be set as system property, use <argLine>-Dfile.encoding=...</argLine> instead [INFO] [INFO] ------------------------------------------------------- [INFO] T E S T S [INFO] ------------------------------------------------------- [INFO] Running com.logicbig.example.ControllerTest request body: User{name='joe', emailAddress='joe@example.com'} request headers [Content-Type:"application/json", testHeader:"headerValue", Content-Length:"50"] request method : POST [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.030 s -- in com.logicbig.example.ControllerTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 3.774 s [INFO] Finished at: 2026-07-27T16:18:01+08:00 [INFO] ------------------------------------------------------------------------ INFO: Completed initialization in 1 ms
Example ProjectDependencies and Technologies Used: - spring-webmvc 7.0.6 (Spring Web MVC)
Version Compatibility: 4.1.0.RELEASE - 7.0.6 Version compatibilities of spring-webmvc with this example: Versions in green have been tested.
- spring-test 7.0.6 (Spring TestContext Framework)
- jakarta.servlet-api 6.1.0 (Jakarta Servlet API documentation)
- junit-jupiter-engine 6.0.3 (Module "junit-jupiter-engine" of JUnit)
- jackson-databind 3.0.0 (General data-binding functionality for Jackson: works on core streaming API)
- hamcrest 3.0 (Core API and libraries of hamcrest matcher framework)
- assertj-core 3.26.3 (Rich and fluent assertions for testing in Java)
- JDK 25
- Maven 3.9.11
|