目錄
引言
在實際開發中,單元測試(Junit)是必不可少的操作,那麼在Spring Boot中我們該怎麼使用Junit單元測試呢,這篇文章將揭開Spring Boot中Junit單元測試的神祕面紗。
一、在pom.xml中添加依賴包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
二、Service單元測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {
@Resource
private UserService userService;
@Test
public void selectAll(){
List<User> userList = userService.selectAll();
Assert.assertEquals(3, userList.size());
}
}
三、Controller單元測試
@Controller
public class IndexController {
@RequestMapping("/test")
@ResponseBody
public String toTest(){
return "test";
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class IndexControllerTest {
//mock api用來模擬http請求
@Autowired
private MockMvc mockMvc;
@Test
public void contextLoads() throws Exception{
mockMvc.perform(MockMvcRequestBuilders.get("/test")
.accept(MediaType.APPLICATION_JSON)) //接收的報文格式
.andExpect(MockMvcResultMatchers.status().isOk()) //檢查Http狀態是否正確
.andExpect(MockMvcResultMatchers.content().string("test")); //測試接口返回內容
}
}