springboot單元測試兩種方法實例詳解
這篇文章主要介紹了springboot單元測試兩種方法實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
springboot的單元測試,這里介紹兩種方式,一種是在測試類中添加注解;另一種是在代碼中啟動項目的main方法中繼承接口(也可以寫在其他方法中)。
如 對查看數據庫的連接池信息 進行單元測試
1. 在類上使用注解:
@RunWith(SpringRunner.class)
@SpringBootTest
@RunWith(SpringRunner.class) @SpringBootTest public class RobotsApplicationTests { @Autowired DataSource dataSource; @Test public void test(){ System.out.println(dataSource.getClass()); } }
2. 繼承CommandLineRunner接口
CommandLineRunner:表示在項目啟動完成后 會執(zhí)行該功能,只需將測試的內容寫在其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(">>>>>>>>>>>>>>>服務啟動執(zhí)行,執(zhí)行加載數據等操作<<<<<<<<<<<<<"); System.out.println("DATASOURCE = " + dataSource); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot集成ip2region實現ip白名單的代碼示例
ip2region v2.0 - 是一個離線IP地址定位庫和IP定位數據管理框架,10微秒級別的查詢效率,提供了眾多主流編程語言的 xdb 數據生成和查詢客戶端實現,本文介紹了SpringBoot集成ip2region實現ip白名單的代碼工程,需要的朋友可以參考下2024-08-08SpringCache 分布式緩存的實現方法(規(guī)避redis解鎖的問題)
這篇文章主要介紹了SpringCache 分布式緩存的實現方法(規(guī)避redis解鎖的問題),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11