首页 > 解决方案 > 为什么这个测试 junit 测试返回 400?

问题描述

我有一个看起来像这样的控制器:

@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 方法的更好方法?提前致谢。

标签: javaunit-testingpostjunitmockito

解决方案


您必须添加accept("application/json")).

如果不是,则模拟不接受此内容类型。


推荐阅读