1 pom.xml 测试依赖添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
2 Service业务方法测试
以 UserService 为例,src/test/java ⽬录下添加测试包 com.xxxx.sprinboot.service 定义测试类代码如下 :
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Starter.class})
public class TestUserService {
private Logger log = LoggerFactory.getLogger(TestUserService.class);
@Resource
private UserService userService;
@Before
public void before(){
log.info("单元测试开始...");
}
@Test
public void test01(){
log.info("⽤户记录:{}", userService.queryUserById(1).toString());
}
@Test
public void test02(){
log.info("⽤户记录:{}", userService.queryUserByParams(new
UserQuery()).toString());
}
@After
public void after(){
log.info("单元测试结束...");
}
}
3 控制层接口测试方法
视图层代码使⽤ MockMvc 进⾏测试,以UserCntroller 为例,src/test/java ⽬录下添加测试包 com. xxxx.sprinboot.controller 定义测试类代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Starter.class})
@AutoConfigureMockMvc
public class TestUserController {
private Logger log = LoggerFactory.getLogger(TestUserController.class);
@Autowired
private MockMvc mockMvc;
//⽤户列表查询
@Test
public void apiTest01() throws Exception{
// 构建请求
MockHttpServletRequestBuilder request =
MockMvcRequestBuilders.get("/user/list")
.contentType("text/html") // 指定请求的contentType头信息
.accept(MediaType.APPLICATION_JSON); // 指定请求的Accept头信息
// 发送请求,获取请求结果
ResultActions perform = mockMvc.perform(request);
// 请求结果校验
perform.andExpect(MockMvcResultMatchers.status().isOk());
// 表示执⾏完成后返回相应的结果
MvcResult mvcResult = perform.andReturn();
// 得到执⾏后的响应
MockHttpServletResponse response = mvcResult.getResponse();
log.info("响应状态:{}", response.getStatus());
log.info("响应内容:{}", response.getContentAsString());;
}
// ⽤户名记录查询
@Test
public void apiTest02() throws Exception{
MvcResult mvcResult =
mockMvc.perform(MockMvcRequestBuilders.get("/user/admin")).
andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
log.info("响应状态:{}",mvcResult.getResponse().getStatus());
log.info("响应内容:{}",mvcResult.getResponse().getContentAsString());;
}
}