为什么此测试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 方法的更好方法?提前谢谢。

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

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

最新更新