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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM