Почему этот тест junit возвращает 400? - PullRequest
0 голосов
/ 16 января 2020

У меня есть контроллер, который выглядит следующим образом:

@PostMapping(path = "/email", consumes = "application/json", produces = "application/json")
public String  notification(@RequestBody EmailNotificationRequest emailNotificationRequest) throws IOException {
    String jobId = emailNotificationRequest.getJobId();
    try {
        service.jobId(jobId);
        return jobId;

    } catch (ApplicationException e) {
        return "failed to send email to for jobId: " + jobId;
    }
}

И я пытаюсь проверить контроллер, но возвращаю 400:

@Before
public void setUp() {
    this.mvc = MockMvcBuilders.standaloneSetup(emailNotificationController).build();
}

@Test
public void successfulServiceCallShouldReturn200() throws Exception {

    String request = "{\"jobId\" : \"testId\"}";

    MvcResult result = mvc.perform(post("/email")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().json(request))
            .andReturn();

    String content = result.getResponse().getContentAsString();

    assertThat(content, isNotNull());

}

Теперь я понимаю, что 400 означает запрос плохой. Поэтому я попытался сделать свой собственный запрос и затем превратить его в строку JSON, например, так:

@Test
public void successfulServiceCallShouldReturn200() throws Exception {
    EmailNotificationRequest emailNotificationRequest = new emailNotificationRequest();
    emailNotificationRequest.setJobId("testJobId");

    MvcResult result = mvc.perform(post("/notification/email")
            .content(asJsonString(emailNotificationRequest))
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();

    assertThat(result, isNotNull());

}

public static String asJsonString(final Object obj) {
    try {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        final String jsonContent = mapper.writeValueAsString(obj);
        return jsonContent;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Я думаю, что это как-то связано с content (), так как я получаю 400, и это должно делать с фактическим запросом. Может кто-нибудь подскажите, пожалуйста, почему запрос все еще плох? Или лучший способ проверить этот конкретный метод POST? Заранее спасибо.

1 Ответ

0 голосов
/ 16 января 2020

Вы должны добавить accept("application/json")).

Если макет не принимает этот тип контента.

...