java - 为什么这个测试 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"))
.
如果不是,则模拟不接受此内容类型。
推荐阅读
- java - 如何使用 Byte Buddy 创建具有由每个枚举常量初始化的字段的枚举?
- php - 如何在 Laravel5.8 中以表单形式防止 Summernote 中的跨站脚本
- kubernetes - Spring Cloud Kubernetes:无法读取带有名称的 configMap
- python - PyInstaller dist EXE 消失
- flutter - 如何强制 Flutter/Dart 要求类型?
- spring - 无法从 Spring Boot 应用程序 yaml 文件中解析值
- sql-server - How do I Select an aggregate function from a temp table without getting the invalid column error from not including the column in the GROUP BY clause?
- r - 正则表达式 - 匹配字符后的所有数字
- excel - 如何使用 VBA 将 Excel 数据插入 Word,并将其导出为 PDF?
- c# - NavigationViw 不根据 PrimaryLanguageOverride 更改语言