SpringBootTest单元测试实战、SpringBoot测试进阶高级篇之MockMvc讲解

1、@SpringBootTest单元测试实战
简介:讲解SpringBoot的单元测试
1、引入相关依赖


org.springframework.boot
spring-boot-starter-test
test



2、使用
测试类:
@RunWith(SpringRunner.class)//底层用junitSpringJUnit4ClassRunner
@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程
public class SpringBootTests { }
【SpringBootTest单元测试实战、SpringBoot测试进阶高级篇之MockMvc讲解】
2、SpringBoot测试进阶高级篇之MockMvc讲解
简介:讲解MockMvc类的使用和模拟Http请求实战

1、增加类注解 @AutoConfigureMockMvc
@SpringBootTest(classes={XdclassApplication.class})
2、相关API
perform:执行一个RequestBuilder请求
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn:最后返回相应的MvcResult->Response
代码示例:
SampleControler.java:

1 package net.xdclass.demo.controller; 2 3 import java.util.Date; 4 import java.util.HashMap; 5 import java.util.Map; 6 7 import org.springframework.boot.*; 8 import org.springframework.boot.autoconfigure.*; 9 import org.springframework.web.bind.annotation.*; 10 11 import net.xdclass.demo.domain.User; 12 13 @RestController 14 public class SampleControler { 15 16@RequestMapping("/test/home") 17public String home() { 18return "xdclass"; 19} 20 21 }

测试:
MockMvcTestDemo.java:
1 package xdclass_springboot.demo; 2 3 import net.xdclass.demo.XdClassApplication; 4 5 import org.junit.Test; 6 import org.junit.runner.RunWith; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 9 import org.springframework.boot.test.context.SpringBootTest; 10 import org.springframework.test.context.junit4.SpringRunner; 11 import org.springframework.test.web.servlet.MockMvc; 12 import org.springframework.test.web.servlet.MvcResult; 13 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 14 import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 16 17 18 /** 19* 功能描述:测试mockmvc类 20*/ 21 @RunWith(SpringRunner.class)//底层用junitSpringJUnit4ClassRunner 22 @SpringBootTest(classes={XdClassApplication.class}) //启动整个springboot工程 23 @AutoConfigureMockMvc 24 public class MockMvcTestDemo { 25 26 27@Autowired 28private MockMvc mockMvc; 29 30 31 32@Test 33public void apiTest() throws Exception { 34 35MvcResult mvcResult =mockMvc.perform( MockMvcRequestBuilders.get("/test/home_xxx") ). 36andExpect( MockMvcResultMatchers.status().isOk() ).andReturn(); 37int status = mvcResult.getResponse().getStatus(); 38System.out.println(status); 39 40} 41 42 }



1、@SpringBootTest单元测试实战简介:讲解SpringBoot的单元测试1、引入相关依赖org.springframework.bootspring-boot-starter-testtest

2、使用@RunWith(SpringRunner.class)//底层用junitSpringJUnit4ClassRunner@SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程public class SpringBootTests { }

    推荐阅读