gpt4 book ai didi

java - 为什么此测试 junit 测试返回 400?

转载 作者:行者123 更新时间:2023-12-01 18:48:25 25 4
gpt4 key购买 nike

我有一个看起来像这样的 Controller :

@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;
}
}

我正在尝试测试 Controller ,但得到了 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 - 为什么此测试 junit 测试返回 400?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com