Spring Boot Test 入门

Spring Boot Test入门

pom文件

需要在项目根目录下pom.xml文件,添加spring boot test依赖的jar包:

<dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-test</artifactId>

         <scope>test</scope>

</dependency>

Service单元测试

  • 创建测试类,在测试类的类头部添加:@RunWith(SpringRunner.class)和@SpringBootTest注解,在测试方法的前添加@Test,最后选择方法右键run运行。
  • 使用@Autowired注入需要测试的类。

示例:

@RunWith(SpringRunner.class)

@SpringBootTest

public class StudentServiceTest {

    @Autowired

    private StudentService studentService;

 

    @Test

         public void getStudent() throws Exception {

                   Student student = studentService.getStudent("1001");

        Assert.assertEquals(16, student.getAge());

         }

}

Controller单元测试

  • 创建测试类,在测试类的类头部添加:@RunWith(SpringRunner.class)、@SpringBootTest、@ AutoConfigureMockMvc注解,在测试方法的前添加@Test,最后选择方法右键run运行。
  • 使用@Autowired 注入MockMvc,在方法中使用 mvc测试功能。

示例:

@RunWith(SpringRunner.class)

@SpringBootTest

@AutoConfigureMockMvc

public class StudentControllerTest {

 

         @Autowired

    private MockMvc mvc;

 

         @Test

         public void getAll() throws Exception {

                   mvc.perform(MockMvcRequestBuilders.get("/student/getAll"))

                            .andExpect(MockMvcResultMatchers.model().attributeExists("students"));

         }

 

         @Test

         public void save() throws Exception {

                   Student student = new Student();

                   student.setAge(12);

                   student.setId("1003");

                   student.setName("hehe");

                   mvc.perform(MockMvcRequestBuilders.post("/student/save", student));

         }

 

         @Test

         public void delete() throws Exception {

                   mvc.perform(MockMvcRequestBuilders.delete("/student/delete?id=1002"));

         }

        

         @Test

         public void index() throws Exception {

                   mvc.perform(MockMvcRequestBuilders.get("/student/index")).andReturn();

         }

}

注意:spring boot 版本是基于 1.4.7.RELEASE

 

posted @ 2017-10-19 17:11  阿谦  阅读(1895)  评论(1编辑  收藏  举报