springboot 測試時bean無法注入的問題

2021-10-03 03:24:41 字數 1562 閱讀 7253

今天在使用springboot 測試的時候時遇到了乙個很坑的問題,自己明明注入了bean,但就是拿不到.情況如下:

於是自己在controller測試看看到底注入了沒,開啟瀏覽器,發現確實注入了啊

那咋測試時獲取的偏偏是null. 我懷疑自己是不是沒有使用上spring的測試模組,或者說@springboottest註解失效了,反正就是springboot測試 沒有正常執行.後來我才明白,由於自己的專案不是使用spring initializr建立的,是不是因為找不到主測試類無法注入,直接當做物件宣告了,所以為才null.

於是我又開啟正常的spring initializr建立的專案,在test包下做了乙個驗證.發現如果不在主測試類所在包及其子包下,可能直接報錯,test包結構和錯誤如下:

於是點開@springboottest,部分原始碼如下:

@target

(elementtype.type)

@retention

(retentionpolicy.runtime)

@documented

@inherited

@bootstrapwith

class

)@extendwith

(springextension.

class

)public @inte***ce

springboottest

. if no

* explicit classes are defined the test will look for nested

* classes, before falling back to a

* search.

* @see contextconfiguration#classes()

*/class<

?>

classes()

default

;

所以如果我們的測試類沒有位於主測試類所在包及其子包下,那麼就搜尋不到,當然就沒有spring的測試環境,當然也無法自動注入.

@springboottest

(classes =

class})

@runwith

(springrunner.

class

)

我第一次遇到的可能就是這種情況,修改後再測試一切正常:

SpringBoot實現單元測試時回滾事務

springboot跑個單元測試只需要在測試類加兩個註解就行了。runwith springrunner.class springboottest然而這樣的單元測試預設是提交事務的,一般的場景下都是要對事務進行回滾的。要支援回滾,只需要增加乙個 transactional註解即可。runwith s...

springboot快取測試

配置pom.xml加入快取依賴 org.springframework.boot spring boot starter cache 程式入口加上註解 enablecaching快取對應的實體類序列化 implements serializable 在快取的需要快取的service 加上 cache...

spring boot 入門測試

主啟動類 public static void main string args yml是有層級關係的 1.注意縮排2.key與值之間注意加空格 server port 8091 servlet context path 可以通過yml檔案實現物件的屬性賦值 user id 1 username h...