我对使用 Spring 进行单元测试还很陌生,无法弄清楚为什么当请求正文为空时 MockMvc 不能与 post 一起使用。我得到的错误:java.lang.AssertionError:Response status expected:<200> but was <404>
。我已经让 get 端点正常工作,所以我认为其余控制器接线正确。我只是想知道当 POST 或 PUT 请求缺少正文但有参数时如何编写单元测试。我尝试了以下不同的变体,例如链接 .contentType(MediaType.ALL).content("")
,但我总是遇到相同的错误。
UnitTest.java
@Test
public void shouldCreateSomething() throws Exception{
mockMvc.perform(post(somethingUri).param(idParameter, fieldParameter))
.andExpect(status().is(200));
}
RestAPI.java
@Operation(summary = "Updates something", responses = {
@ApiResponse(responseCode = "200", description = "Something was updated"),
@ApiResponse(responseCode = "406", description = "Something was invalid") })
@PutMapping(value = somethingUri)
public void updateSomething(
@Parameter(description = "Something's id", required = true) @RequestParam String id,
@Parameter(description = "Something's name to be updated", required = true) @RequestParam String name)
{
System.out.println("please work");
}
答案 0 :(得分:0)
我的代码最终出现了 2 个问题。
404 错误可能是由不正确的 URI 引起的。
随后出现的 400 错误是由我的格式错误的 param
引起的。应该是:
@Test
public void shouldCreateSomething() throws Exception{
mockMvc.perform(post(somethingUri)
.param(idPropName, idParameter)
.param(fieldPropName,fieldParameter))
.andExpect(status().is(200));
}
所以和空的身体完全没有关系