import com.fasterxml.jackson.databind.ObjectMapper;
import com.fengzhe.open.module.vo.ParamVo;
import lombok.extern.slf4j.Slf4j;
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;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.nio.charset.Charset;
@Slf4j
@SpringBootTest
@AutoConfigureMockMvc
class XXControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Test
void XXPostMethod() {
ParamVo vo = new ParamVo();
vo.setName("王德发");
vo.setCompanyTel("0755-12546454545454");
vo.setInvoiceTileType("B1");
vo.setSendEmail("46578794564546456465456@qq.com");
vo.setTaxNo("7897456464645454654412356465112");
MvcResult mvcResult;
try {
mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/api/channels/XXPostMethod")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(vo))
.accept(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
//MvcResult默认编码是ISO-8859-1 手动转一下utf-8
log.info(mvcResult.getResponse().getContentAsString(Charset.defaultCharset()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
void XXGetMethod () {
MvcResult mvcResult;
try {
mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/api/channels/XXGetMethod")
.accept(MediaType.APPLICATION_JSON)
.param("name", "张三").param("pass", "123456")
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
log.info(mvcResult.getResponse().getContentAsString(Charset.defaultCharset()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
@SpringBootTest单元测试示例
最新推荐文章于 2024-06-28 08:00:00 发布
该博客展示了如何使用Spring Boot的MockMvc进行单元测试,包括POST和GET请求的方法。在测试中,创建了ParamVo对象并设置了相关参数,然后发送JSON请求到指定API路径,检查响应状态并记录响应内容。
摘要由CSDN通过智能技术生成