gpt4 book ai didi

java - 在测试中排除一些bean

转载 作者:行者123 更新时间:2023-11-28 21:37:14 25 4
gpt4 key购买 nike

我的应用程序中有此配置(EngineConfig.java):

@Component
@EnableAutoConfiguration
@EnableCaching
@EnableScheduling
@ComponentScan(basePackages = "com.exaple.package")
public class EngineConfig {

}

在包中我有包components,其中包含一些bean标记注释@Component:

enter image description here

所以,我有一些测试:

@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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com