![](/img/trans.png)
[英]Spring Boot 2.5.0 - REST controller, MockMvc not UTF-8
[英]How to set consumes and produces of rest controller in mockmvc using Spring boot?
我有這樣一個 controller;
@RestController
@RequestMapping(GA)
@RequiredArgsConstructor
public class GaController {
private final GaService service;
@PostMapping(value = INITIALIZE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<GaDTO> initialize() {
return status(CREATED).body(service.initialize());
}
@GetMapping(value = FIND, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<GaDTO> find(@PathVariable String id) {
return ok().body(service.find(id));
}
@PutMapping(value = PLAY, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<GaDTO> play(@Valid @RequestBody Request request) {
return ok().body(service.play(request));
}
@DeleteMapping(value = DELETE)
public ResponseEntity<Void> delete(@PathVariable String id) {
service.delete(id);
return status(NO_CONTENT).build();
}
}
在我的單元測試中,我使用@WebMvcTest
和@MockMvc
但我不知道如何在mockMvc
中設置produces
和consumes
配置。
這是一個例子;
@Test
public void initialize_success() throws Exception {
when(gaService.initialize()).thenReturn(gaDTO);
mockMvc.perform(post(GA + INITIALIZE)
.contentType(APPLICATION_JSON))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id", is(gaDTO.getId())));
}
這是真的? 我的意思是, .contentType(APPLICATION_JSON)
指的是produces
還是consumes
?
我不知道 SpringBoot 是否屬於這種情況,但是對於 JPA,您應該具有可以放在方法上方的注釋 @Consumes 和 @Produces。
例如,您可以放置 @Consumes(MediaType.APPLICATION_JSON) 或 @Produces(MediaType.TEXT_PLAIN)
鑒於 MediaType 也可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.