springboot單元測試兩種方法實例詳解
這篇文章主要介紹了springboot單元測試兩種方法實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
springboot的單元測試,這里介紹兩種方式,一種是在測試類中添加注解;另一種是在代碼中啟動項目的main方法中繼承接口(也可以寫在其他方法中)。
如 對查看數(shù)據(jù)庫的連接池信息 進行單元測試
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í)行該功能,只需將測試的內(nèi)容寫在其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(">>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
System.out.println("DATASOURCE = " + dataSource);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解Springboot應用啟動以及關(guān)閉時完成某些操作
這篇文章主要介紹了詳解Springboot應用啟動以及關(guān)閉時完成某些操作,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11
SpringBoot集成ip2region實現(xiàn)ip白名單的代碼示例
ip2region v2.0 - 是一個離線IP地址定位庫和IP定位數(shù)據(jù)管理框架,10微秒級別的查詢效率,提供了眾多主流編程語言的 xdb 數(shù)據(jù)生成和查詢客戶端實現(xiàn),本文介紹了SpringBoot集成ip2region實現(xiàn)ip白名單的代碼工程,需要的朋友可以參考下2024-08-08
SpringCache 分布式緩存的實現(xiàn)方法(規(guī)避redis解鎖的問題)
這篇文章主要介紹了SpringCache 分布式緩存的實現(xiàn)方法(規(guī)避redis解鎖的問題),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11
Spring在多線程下保持事務(wù)的一致性的方法實現(xiàn)
當Spring在多線程環(huán)境下運行時,確保事務(wù)一致性是非常重要的,本文主要介紹了Spring在多線程下保持事務(wù)的一致性的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,需要的朋友們下面隨著小編來一起學習學習吧2024-01-01

