以下是一个使用 Mvc
框架(例如 Spring MVC 测试框架)中的 Mvc.perform(post(""))
方法的示例代码:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@SpringBootTest
@AutoConfigureMockMvc
public class YourControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testYourPostEndpoint() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/yourEndpoint")
.param("param1", "value1")
.param("param2", "value2"))
.andExpect(status().isOk());
}
}
在上述示例中,假设您有一个名为 /yourEndpoint
的 POST 端点,通过 param
方法设置了请求参数,并期望返回的状态码为 200 OK
。
您可以根据自己的实际需求修改端点路径、请求参数和预期的响应。请问这个示例对您有帮助吗?或者您能提供更多关于您具体使用场景的信息,以便我为您提供更贴合您需求的示例。
以下是一个 Mvc.perform(post(""))
入参为实体类的示例代码,假设我们有一个用户实体类 User
:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class YourControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testPostWithEntity() throws Exception {
User user = new User();
user.setName("John Doe");
user.setAge(30);
mockMvc.perform(post("/yourEndpoint")
.contentType(MediaType.APPLICATION_JSON)
.content(JSONObject.toJSONString(user)))
.andExpect(status().isCreated());
}
// 假设的 User 类
static class User {
private String name;
private int age;
// 相应的 getter 和 setter 方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
在上述示例中,创建了一个 User
实体对象,并使用 ObjectMapper
将其转换为 JSON
字符串作为请求体发送 POST
请求。