4
4
.
.
3
3
.
.
7
7
T
T
e
e
s
s
t
t
-
-
R
R
e
e
s
s
p
p
o
o
n
n
s
s
e
e
-
-
B
B
o
o
d
d
y
y
-
-
T
T
e
e
x
x
t
t
I
I
n
n
f
f
o
o
[
[
G
G
]
]
[
[
R
R
]
]
This tutorial shows how to test if Controller returned valid Text in Response Body.
Application Schema [Result]
Spring Boot Starters
GROUP
DEPENDENCY
DESCRIPTION
Web
Spring Web
Enables: Controller Annotations, Tomcat Server
Syntax
//CREATE REQUEST
MockHttpServletRequestBuilder request = get("/Hello?name=John");
//PERFORM REQUEST. RETURN RESULT.
MvcResult mvcResult = mockMvc.perform(request).andReturn();
String responseBody = mvcResult.getResponse().getContentAsString();
//CHECK RESPONSE BODY
assertEquals("Hello John", responseBody);
http://localhost:8080/Hello?name=John
Tomcat
hello()
MyController
MyControllerTest
P
P
r
r
o
o
c
c
e
e
d
d
u
u
r
r
e
e
Create Project: springboot_test_mockmvc_response_body (add Spring Boot Starters from the table)
Create Package: controllers (inside main package)
– Create Class: MyController.java (inside controllers package)
Create Test Class: MyControllerTest.java
MyController.java
package com.ivoronline.springboot_test_mockmvc_response_body.controllers;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@ResponseBody
@GetMapping("/Hello")
public String hello(@RequestParam String name) {
return "Hello " + name;
}
}
MyControllerTest.java
package com.ivoronline.springboot_test_mockmvc_response_body.controllers;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
@WebMvcTest
class MyControllerTest {
@Autowired MockMvc mockMvc;
@Autowired MyController myController;
@Test
void hello() throws Exception {
//CREATE REQUEST
MockHttpServletRequestBuilder request = get("/Hello?name=John");
//PERFORM REQUEST. RETURN RESULT.
MvcResult mvcResult = mockMvc.perform(request).andReturn();
String responseBody = mvcResult.getResponse().getContentAsString();
//CHECK RESPONSE BODY
assertEquals("Hello John", responseBody);
}
}
R
R
e
e
s
s
u
u
l
l
t
t
http://localhost:8080/Hello?name=John
Wrong Response Body assertEquals("Hello John1", responseBody)
org.opentest4j.AssertionFailedError:
Expected :Hello John1
Actual :Hello John
Run Test Class: MyControllerTest.java
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>