簡體   English   中英

如何使用 Spring 引導在 mockmvc 中設置 rest controller 的消費和生產?

[英]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中設置producesconsumes配置。

這是一個例子;

@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM