junit啓動報錯 Unable to find a @SpringBootConfiguration

環境java

springboot項目的junit測試spring

工程結構:springboot

test類代碼以下:測試

 

問題spa

控制檯中拋出以下異常:3d

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your testblog

 

緣由ci

項目SpringBoot啓動類路徑爲com.eddue.datav下與測試類com.eddue.biz不一致。由於@SpringBootTest會自動查詢@SpringBootConfiguration,在com.eddue.biz類路徑下搜索@SpringBootConfiguration。然而java源代碼的類路徑爲com.eddue.datav下的ServerApplication的@SpringBootApplication中引用了@SpringBootConfiguration,這裏纔有@SpringBootConfiguration註解。所以致使沒法查詢到@SpringBootConfiguration註解,致使沒法加載springboot啓動類ServerApplication。it

參考SpringBootTest下類註釋io

Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit  classes are specified.

意思是:會自動搜尋一個@SpringBootConfiguration,當不使用嵌套@Configuration,也沒有明確指定類


解決方案

下面提供兩種解決方案,選擇其中任一方案便可

1:修改工程結構,將測試類路徑com.eddue.biz改成com.eddue.datav,使自動掃描能查詢到。

2:修改測試類代碼,將測試類代碼@SpringBootTest改成@SpringBootTest(classes = ServerApplication.class),手動指定springboot啓動類路徑。

 

測試結果

兩種解決方案都能正常加載springboot啓動,並正常運行junit的test方法

相關文章
相關標籤/搜索