我的应用程序中有此配置(EngineConfig.java
):
@Component
@EnableAutoConfiguration
@EnableCaching
@EnableScheduling
@ComponentScan(basePackages = "com.exaple.package")
public class EngineConfig {
}
在包中我有包components
,其中包含一些bean标记注释@Component
:
所以,我有一些测试:
@ContextConfiguration(classes = [
EngineConfig::class
])
@RunWith(SpringRunner::class)
class EngineTest {
@Test
fun factorial() {
//some test
}
}
问题是 components 文件夹中的一些 bean 需要一个数据源,但在这个测试中我不需要使用数据库,所以没有创建数据源。是否可以在测试中指定 Spring 不创建一些未找到 Autowiring 候选的 bean?因此,我收到这样的错误:
Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]
但是在这个测试中我不需要使用基础,所以我想排除一些 beans 的创建。
最佳答案
您应该使用 Spring 配置文件。在配置文件中将数据源定义为 bean:
@Configuration
public class EngineConfig {
@Bean
@Profile("!test")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
// define it here
return dataSource;
}
}
然后在你的测试中使用这个注释来使用测试配置文件:
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
class EngineTest {
}
这样它就不会定义数据源 bean。
关于java - 在测试中排除一些bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57037311/