本隨筆記錄使用Spring Boot進行單元測試,主要是Service和API(Controller)進行單元測試。
一、Service單元測試
選擇要測試的service類的方法,使用idea自動創建測試類,步驟如下。(注,我用的是idea自動創建,也可以自己手動創建)
自動創建測試類之后目錄如下圖:
測試類StudentServiceTest.java代碼如下:
package *; //自己定義路徑 import *.Student; //自己定義路徑 import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest public class StudentServiceTest { @Autowired private StudentService studentService; @Test public void findOne() throws Exception { Student student = studentService.findOne(1); Assert.assertEquals(new Integer(16), student.getAge()); } }
二、API(Controller)單元測試
根據上面的步驟創建單元測試類StudentControllerTest.java,代碼如下:
package *; //自己定義路徑 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class StudentControllerTest { @Autowired private MockMvc mvc; @Test public void getStudentList() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/students")) .andExpect(MockMvcResultMatchers.status().isOk()); //.andExpect(MockMvcResultMatchers.content().string("365")); //測試接口返回內容 } }
三、service和API(Controller)類和方法
StudentController.java代碼如下:
package *; //自己定義路徑 import *.StudentRepository; //自己定義路徑 import *.Student; //自己定義路徑 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController public class StudentController { @Autowired private StudentRepository studentRepository; /** * 查詢學生列表 * @return */ @GetMapping(value = "/students") public List<Student> getStudentList(){ return studentRepository.findAll(); } }
StudentService.java代碼如下:
package *; //自己定義路徑 import *.StudentRepository; //自己定義路徑 import *.Student; //自己定義路徑 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentService { @Autowired private StudentRepository studentRepository; /** * 根據ID查詢學生 * @param id * @return */ public Student findOne(Integer id){ return studentRepository.findOne( id); } }