Spring Boot 提供了一些實用程序和注解,用來幫我們測試應用程序。測試由兩個模塊支持——spring-boot-test包含了核心項目,而spring-boot-test-autoconfigure支持自動配置測試。
使用
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
例子
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
@Autowired
DeviceService deviceService; //要測試的service
@BeforeClass
public static void classBefore() {
System.out.println("在每個類加載之前執行");
}
@AfterClass
public static void classAfter() {
System.out.println("在每個類加載之后執行");
}
@Before
public void before() {
System.out.println("在每個測試方法之前執行");
}
@After
public void after() {
System.out.println("在每個測試方法之后執行");
}
/**
* 測試service
*/
@Autowired
UserService userService;
@Test
//事務回滾
@Transactional
public void updateLoginTime() {
int i = userService.updateLoginTime(1);
Assert.assertEquals(1, i);
}
private MockMvc mvc;
private MockMvc loginMvc;
@Before
public void setUp() throws Exception {
//初始化
mvc = MockMvcBuilders.standaloneSetup(new CentralMonitorController()).build();
loginMvc = MockMvcBuilders.standaloneSetup(new LoginController()).build();
}
/**
* 測試controller調用 這里只測試url調用,GET
* @throws Exception
*/
@Test
public void list() throws Exception {
String url = "/central/wesker/group/list";
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(url).accept(MediaType.APPLICATION_JSON)).andReturn();
int status = mvcResult.getResponse().getStatus();
Assert.assertEquals(200, status);
String content = mvcResult.getResponse().getContentAsString();
System.out.println("content : " + content);
}
/**
* 測試controller調用,POST
* @throws Exception
*/
@Test
public void login() throws Exception {
Map<String,String> user = new HashMap<>(3);
user.put("admin","wesker");
user.put("pwd","123");
String url = "/central/login";
MvcResult mvcResult = loginMvc.perform(MockMvcRequestBuilders.post(url)
.content(JSON.toJSONString(user))
.contentType(MediaType.APPLICATION_JSON))
.andReturn();
int status = mvcResult.getResponse().getStatus();
Assert.assertEquals(200, status);
String content = mvcResult.getResponse().getContentAsString();
System.out.println(content);
}
@RunWith 是JUnit標準和一個注解,用來告訴JUnit單元測試框架不要使用內置的方式進行單元測試,而應使用 RunWith 指明的類來提供單元測試,所有的 Spring 單元測試總是使用SpringRunner.class
@SpringBootTest 用于 Spring Boot 應用測試, 它默認會根據包名逐級往上找,一直找到 Spring Boot 主程序,也就是通過類注解是否包含@SpringBootApplication來判斷是否是主程序,并在單元測試的時候啟動該類來創建Spring上下文環境。
@Transactional 是用于事務回滾的注解。因為此處測試的是往數據庫里添加數據,我們希望Service測試完畢后,數據能自動回滾。但nosql一般不支持回滾
單元測試中不準使用System.out進行人肉驗證,必須使用assert進行驗證