版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Springboot集成单元测试--接口测试
基本
1.RunWith基于spring的JUnit
2.MockMvc 这个是可以用来模拟接口调用的类
3.SpringBootTest这个基于springboot,classes后面就是springboot的启动类
// test类基本代码
@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,classes = Application.class)
@ActiveProfiles("package")//这个可以不写,可以指定固定yml文件读取,像加了这个,就是读取application-package.yml 文件
public class ApplicationTests {
@Autowired
MockMvc mockMvc;
@Test
public void TestcontextLoads() {
}
}
接口参数的传递,对应单元测试的参数怎么处理
- 使用@PathVariable注解参数
这类参数是带在请求路径后面的但在是在?前面的参数
// 对用的
MvcResult mvcResult = mockMvc.perform(
//这个里get,post,put,delete分别对用自己接口设定里面是url,{id}是PathVariable注解传递参数,后面是值
get("/test/test_url/{Id}/{name}","1","2222")
//设定一些基本,json传递
.contentType(MediaType.APPLICATION_JSON))
// 期待返回的服务器状态码 200,500,404等等
.andExpect(status().isOk())
.andReturn();
//输出返回内容
System.out.println(mvcResult.getResponse().getContentAsString());
- 使用@RequestParam注解参数
这类参数是带在请求路径?后面的参数
// 对用的
MvcResult mvcResult = mockMvc.perform(
//这个里get,post,put,delete分别对用自己接口设定里面是url,{id}是PathVariable注解传递参数,后面是值
get("/test/test_url")
//设定一些基本,json传递
.contentType(MediaType.APPLICATION_JSON))
.param("name","测试")
.param("value","测试多个")
// 期待返回的服务器状态码 200,500,404等等
.andExpect(status().isOk())
.andReturn();
//输出返回内容
System.out.println(mvcResult.getResponse().getContentAsString());
- 使用@RequestBody注解参数
这个参数是分装好的
// 对用的
Map<String,Object> map = new HashMap<>(4);
map.put("name","测试");
map.put("value","测试多个")
MvcResult mvcResult = mockMvc.perform(
//这个里get,post,put,delete分别对用自己接口设定里面是url,{id}是PathVariable注解传递参数,后面是值
get("/test/test_url")
//设定一些基本,json传递
.contentType(MediaType.APPLICATION_JSON)
//这里转成json
.content(JSONObject.toJSONString(map)))
// 期待返回的服务器状态码 200,500,404等等
.andExpect(status().isOk())
.andReturn();
//输出返回内容
System.out.println(mvcResult.getResponse().getContentAsString());
返回值校验
Assert.assertEquals(expected, actual);//expected期待值,actual实际值,对比过后,如果都成功,那么正常