我正在尝试做类似的事情:
mockMvc
.perform(post("/forums/{forumId}/register", 42L)
.contentType("application/json")
.param("sendWelcomeMail", "true")
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isOk());
但是.content方法在5.2.6中消失了,现在似乎有一个body()函数:
mockMvc
.perform(post("/conversions/ktoc")
.contentType(MediaType.APPLICATION_JSON)
.body(objectMapper.writeValueAsString(request)). /*missing method to get back to Builder*/
.andExpect(status().isOk());
有人可以提供帮助,我在网上找到的所有示例都指向使用content(..)方法
根据.content()
,在Spring Test 5.2.6中仍然应该有docs方法。
您的代码可能发生的事情是,您从MockMvcRequestBuilders
导入了org.springframework.mock.http.server.reactive.MockServerHttpRequest.post
的反应型,实际上它没有.content()
方法,只有.body()
。
因此请确保将Servlet版本导入测试中:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest
class PublicControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testMe() throws Exception {
this.mockMvc
.perform(post("/test").content("Some content"))
.andExpect(status().isOk());
}
}