我有一个看起来像这样的控制器:
@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方法的更好方法?预先感谢。
答案 0 :(得分:0)
您必须添加class MyPojo {
private final EnumMap<MyEnum, String> fields = new EnumMap<>(MyEnum.class);
public String matchMethod(MyEnum myenum) {
return fields.get(myenum);
}
public void setField1(String value) {
fields.put(MyEnum.FIELD1, value); // for example
}
}
。
如果不是,则模拟不接受此内容类型。