springboot的單元測試,這裏介紹兩種方式,一種是在測試類中添加註解;另外一種是在代碼中啓動項目的main方法中繼承接口(也能夠寫在其餘方法中)。spring
如 對查看數據庫的鏈接池信息 進行單元測試數據庫
1. 在類上使用註解:springboot
@RunWith(SpringRunner.class) session
@SpringBootTestide
@RunWith(SpringRunner.class) @SpringBootTest public class RobotsApplicationTests { @Autowired DataSource dataSource; @Test public void test(){ System.out.println(dataSource.getClass()); } }
2. 繼承CommandLineRunner接口單元測試
CommandLineRunner:表示在項目啓動完成後 會執行該功能,只需將測試的內容寫在其run()方法中,如:測試
@SpringBootApplication @EnableScheduling @ComponentScan(basePackages={"com.cmit.hall.plat","com.cmit.hall.pub"}) @ServletComponentScan(value= {"com.cmit.hall.pub.interceptor","com.cmit.hall.plat.config","com.cmit.hall.pub.session"}) @EnableRedisHttpSession(maxInactiveIntervalInSeconds=1800) public class PlatApp implements CommandLineRunner { @Autowired DataSource dataSource; public static void main(String[] args) { SpringApplication.run(PlatApp.class, args); } @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啓動執行,執行加載數據等操做<<<<<<<<<<<<<"); System.out.println("DATASOURCE = " + dataSource); } }