[英]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.