(一)Controller层测试
//测试环境 @RunWith(SpringRunner.class) //测试注解 @SpringBootTest //测试Controller层专门的注解 @AutoConfigureMockMvc public class GirlControllerTest { //测试Controller层专门的对象 @Autowired private MockMvc mockMvc; @Test public void getGirlById() throws Exception { //请求方法时“GET”,那么就用get()方法 mockMvc.perform(MockMvcRequestBuilders.get("/girls/3")) //期望返回的Status是200 .andExpect(MockMvcResultMatchers.status().isOk()) //期望返回的数据是“abc” .andExpect(MockMvcResultMatchers.content().string("abc")); } }
(二)Service层测试
//测试环境 @RunWith(SpringRunner.class) //测试注解 @SpringBootTest public class GirlServiceImplTest { //注入Service对象 @Autowired private GirlServiceImpl girlServiceImpl; @Test public void getGirlById() throws Exception { Girl girl = girlServiceImpl.getGirlById(3); Assert.assertEquals(new Integer(15), girl.getAge()); } }
文章来源: 九、SpringBoot入门之单元测试