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:表示在項目啟動完成后 會執行該功能,只需將測試的內容寫在其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);
    }
}

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM