【发布时间】:2020-10-19 13:20:37
【问题描述】:
我有两个具有相同签名的 bean。它们被命名是为了将正确的实例传递给请求它们的类。
@Configuration
public class MyConfiguration {
@Bean("durationForX")
public Duration durationForX() {
return Duration.ofSeconds(1);
}
@Bean("durationForY")
public Duration durationForY() {
return Duration.ofSeconds(5);
}
}
并用作
@Component
public class MyService {
public MyService(
@Qualifier("durationForX") duration
) {
...
}
}
和 Y 类似。
现在,我想在集成测试中自动装配上述 bean 的模拟。我已经尝试了以下
@Configuration
@Profile("my-test-profile")
public class IntegrationTestConfiguration {
@Primary
@Bean("durationForX")
public Duration durationForXMock() {
return Duration.ofMillis(100);
}
@Primary
@Bean("durationForY")
public Duration durationForYMock() {
return Duration.ofMillis(500);
}
@Primary
@Bean
public AnotherService anotherService() {
// This one works as expected, probably because it is not a named bean
...
}
}
在运行集成测试时会导致错误消息
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'durationForX', defined in class path resource [com/../../MyConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [com/.../.../IntegrationTestConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
我没有在集成测试中自动连接实例本身,只有一个入口点供应用程序调用。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, classes = {MyApp.class})
@ActiveProfiles("it")
class MyIntegrationTest {
@Autowired
GraphQLTestTemplate graphQL;
...
}
我不太热衷于将 bean 覆盖设置为 true,因为我想控制在哪里使用哪些 bean。我希望模拟命名的 bean 遵循与未命名的相同的模式,这是为什么呢?对解决方法有任何想法吗?
【问题讨论】:
标签: java spring-boot testing mocking javabeans