簡體   English   中英

使用私有構造函數對 spring 組件進行單元測試,無需注入

[英]Unit test a spring component with private constructor without injection

我有一個使用私有構造函數注入的@Component -annotated class,以及用於嵌套注入的@Autowired -annotated setter。

為了對其進行單元測試, 我發現一種解決方法是使用@SpringBootTest@DirtiesContext注釋來創建帶有注入組件的 Spring 上下文以進行測試並在每次測試后“重新連接”它。

但是,我想在沒有上下文的情況下對這個組件進行單元測試(以避免在每次測試之前都必須構建所有上下文)。

我可以毫無問題地模擬每個嵌套注入(因為我只想在這里測試 controller)。

因此我的問題是:我怎樣才能“獲取”這個組件的實例? 如何在每次測試前重置它? 那么我應該如何獲得我的模擬嵌套注入(我會 - 我猜 - 通過我的設置器“注入”)?

不要使用私有構造函數。 擁有一個私有構造函數然后使用反射仍然只從外部調用它沒有任何好處。 You should only use a private constructor if the class has only static member to make it clearer that the class is not meant to be instantiated or if you are using a static factory method in the same class to create instances.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM