问题描述
我有一个接口的两个实现 - default 和 dev.我使用 @ConditionalOnProperty
作为默认实现和 @Profile
和 @ConditionalOnMissingBean
的组合用于开发实现.
I have two implementations of one interface - default and dev. I use @ConditionalOnProperty
for default implementation and combination of @Profile
and @ConditionalOnMissingBean
for dev implementation.
@Service
@ConditionalOnProperty(prefix = "keystore", value = "file")
public class DefaultKeyStoreService implements KeyStoreService {
@Service
@Profile("dev")
@ConditionalOnMissingBean(KeyStoreService.class)
public class DevKeyStoreService implements KeyStoreService {
现在,问题出在 DevKeyStoreService
的测试 DevKeyStoreServiceTest
中.我有这样的配置:
Now, the problem is in test DevKeyStoreServiceTest
for DevKeyStoreService
.I have configuration like this:
@SpringBootTest(
classes = {DevKeyStoreService.class},
properties = {"keystore.file="}
)
@RunWith(SpringRunner.class)
@ActiveProfiles("dev")
public class DevKeyStoreServiceTest {
@Autowired
private DevKeyStoreService tested;
@Test
public void testPrivateKey() {
} //... etc.
结果是:
Negative matches:
-----------------
DevKeyStoreService:
Did not match:
- @ConditionalOnMissingBean (types: service.crypto.KeyStoreService; SearchStrategy: all) found bean 'devKeyStoreService' (OnBeanCondition)
和典型的org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为service.crypto.DevKeyStoreServiceTest"的bean时出错...
.
如何配置测试类才能运行它?
How can I configure the test class to be able to run it?
推荐答案
好的,我想通了.
带有值的注释 @ConditionalOnMissingBean(KeyStoreService.class)
试图只找到具体的实例,而 KeyStoreService
接口不是.这样,它找不到任何东西.
Annotation with value @ConditionalOnMissingBean(KeyStoreService.class)
tries to find only concrete instances, which interface KeyStoreService
is not. This way, it doesn't find anything.
当我使用带有类型的注释时,它的作用就像一个魅力:@ConditionalOnMissingBean(type = "KeyStoreService")
.
When I use annotation with type instead, it works like a charm: @ConditionalOnMissingBean(type = "KeyStoreService")
.
这篇关于注释 @ConditionalOnMissingBean 在测试中不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!