本隨筆記錄使用Spring Boot進行單元測試,主要是Service和API(Controller)進行單元測試。java
1、Service單元測試web
選擇要測試的service類的方法,使用idea自動建立測試類,步驟以下。(注,我用的是idea自動建立,也能夠本身手動建立)spring
自動建立測試類以後目錄以下圖:mvc
測試類StudentServiceTest.java代碼以下:app
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()); } }
2、API(Controller)單元測試ide
根據上面的步驟建立單元測試類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")); //測試接口返回內容 } }
3、service和API(Controller)類和方法測試
StudentController.java代碼以下:ui
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代碼以下:idea
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); } }