簡體   English   中英

Spring Boot無法自動裝配測試類

[英]Spring Boot not autowiring class in test

我有一個具有以下結構的Spring Boot 2應用程序:

- src/main/java/com.mycompany/
---- application
---- domain
---- infrastructure
-------- persistence
------------ ...
-------- Application.java
- src/main/test/java/com.mycompany/
---- application
---- domain
---- infrastructure
-------- persistence
------------ testingutils
---------------- JdbcPersistenceHelper.java
------------ CurrenciesJdbcViewTest.java

應用類別:

package com.mycompany.infrastructure;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

JdbcPersistenceHelper:

package com.mycompany.infrastructure.persistence.testingutils;

@Component
public class JdbcPersistenceHelper {

    private EntityManager entityManager;

    @Autowired
    public JdbcPersistenceHelper(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

貨幣JdbcViewTest:

package com.mycompany.infrastructure.persistence;

@DataJpaTest
public class CurrenciesJdbcViewTest {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private JdbcPersistenceHelper persistenceHelper;

    private CurrenciesJdbcView view;

    @BeforeEach
    void setUp() {
        view = new CurrenciesJdbcView(jdbcTemplate);
    }

但是,當我運行測試時,在ApplicationContext加載時出現錯誤,如下所示:

org.springframework.beans.factory.UnsatisfiedDependencyException:創建名稱為'com.mycompany.infrastructure.persistence.CurrenciesJdbcViewTest'的bean時出錯:通過字段'persistenceHelper'表示的不滿意依賴關系; 嵌套的異常是org.springframework.beans.factory.NoSuchBeanDefinitionException:沒有類型為'com.mycompany.infrastructure.persistence.testingutils.JdbcPersistenceHelper'的合格Bean:期望至少有1個有資格作為自動裝配候選的Bean。 依賴項注釋:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}

似乎spring並沒有檢測並自動JdbcPersistenceHelper類,即使它位於com.mycompany.infrastructure的子包中,該子包是我的spring boot的應用程序類所在的位置,因此我認為它應該能夠在沒有任何進一步配置的情況下檢測到它。 我在這里想念什么嗎?

您具有“ src / main / test / com.mycompany /”,但應為“ src / test / java / com / mycompany /”

我猜“測試”被視為軟件包的名稱,因此沒有被組件掃描所識別。

如果要在測試中使用依賴項注入,則可能需要考慮使用構造函數注入,而建議使用字段注入,因為它被認為是更好的樣式和更清晰的(必須設置所有必需的依賴項)。

我想我根本不會在測試中使用DI,而只是將任何幫助程序實例化為字段或@Before方法。 我並不是真正將測試視為應用程序組件,而是將其視為獨立的東西。 降低復雜性有助於理解和維護測試經驗。

您僅在測試類上使用@DataJpaTest 最有可能的,你的“幫手”(我建議使用Spring數據JPA替換)是不是在該切片和需要添加使用它來includeFilters@ContextConfiguration

暫無
暫無

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

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