SpringBoot使用junit非常簡單,我們來看一下,首先說明,這裏使用的是springboot2.0.4的版本
一.pom.xml文件開啓springboot測試包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
二.創建一個測試類
1.單文件測試,直接添加@Test註解即可,如圖:
2.MVC形式調用
測試類,需要加上兩個註解
@RunWith(SpringRunner.class) @SpringBootTest(classes={App.class})
其中App.class是主程序入口類,即springboot的啓動類
package com.qfx.test;
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 com.qfx.system.App;
import com.qfx.system.service.SysUserService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes={App.class})
public class JunitTest {
@Autowired
SysUserService sysUserService;
@Test
public void printSysUserInfo(){
String userStr = sysUserService.getSysUserAll();
System.out.println(userStr);
}
}
進行測試的時候會通過App.class來啓動springboot,我們來看一下效果,如圖:
至於對Controller的測試可以直接啓動項目,通過瀏覽器來發送請求測試了,如果實在想使用junit來測試的話,可以使用來MockMvc進行