【发布时间】:2022-01-20 16:26:08
【问题描述】:
我尝试在春季模拟一个 mvc 请求以测试端到端我的控制器。
post 请求需要一个请求正文,但我收到一个错误 400,告诉我缺少所需的请求正文,即使我使用 MockMvcResultsHandler 打印看到它的正文。
项目架构:
- 源
- 主要
- 测试
- applications.properties
- 控制器
- 服务
这是我的 application.properties
spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=*****
spring.datasource.password=*****
spring.jpa.show-sql = true
这是我的测试
@SpringBootTest
@AutoConfigureMockMvc
public class IntegrationTest {
protected User mockUser;
protected List<User> allUsers;
@Autowired
private MockMvc mvc;
@Autowired
private WebApplicationContext webApplicationContext;
@BeforeEach
public void setUp() {
this.mvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
void testGetAllUsers() throws Exception {
this.mvc.perform(post("/api/users")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("utf-8")
.content("{\"name\":\"name\"}"))
.andDo(print())
.andExpect(status().isCreated());
}
}
我的@RestController
@PostMapping(path = "/users")
public @ResponseBody ResponseEntity<User> addNewUser(
@RequestBody String name
) {
return userService.createUser(name);
}
和我的用户@Service
public ResponseEntity<User> createUser(String name) {
User user = new User();
user.setName(name);
userRepository.save(user);
当我尝试启动测试时,我会进入调试控制台
DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.String> ....addNewType(java.lang.String,java.lang.Boolean)]
MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/users
Parameters = {}
Headers = [Content-Type:"application/json;charset=utf-8", Accept:"application/json", Content-Length:"32"]
Body = {"name":"concat"}
Session Attrs = {}
响应是:
MockHttpServletResponse:
Status = 400
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
当我使用相同的架构时,get 方法似乎有效,主体似乎存在于控制台中,但 servelt 似乎看不到/理解请求主体。
【问题讨论】:
标签: java spring spring-boot spring-mvc mockmvc