Reputation: 961
I am trying to add spring-context-indexer
into the libraries of my project. However, when running an integration test I would like to not use a Bean from a dependency (SystemConfiguration
), but override it using @Primary
to return a new MockSystemConfiguration()
. That doesn't seem to work with the spring-context-indexer.
Here is my test
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = CustomTestSpringConfig.class)
class SpringDataConfigurationTest {
@Test
void applicationContextCanStart() {
assertTrue(true);
}
}
And CustomTestSpringconfig
@Configuration
@ComponentScan(basePackageClasses = SystemConfiguration.class)
public class CustomTestSpringConfig {
@Primary
@Bean(name = "SystemConfiguration")
public SystemConfiguration systemConfiguration() {
return new MockSystemConfiguration();
}
}
The real SystemConfiguration
is defined in a different jar that already has the spring-component-indexer
in it.
@Component("SystemConfiguration")
public class SystemConfigurationImpl implements SystemConfiguration {
What is happening is the real SystemConfiguration
Bean is being used instead of the one annotated with @Primary
.
Upvotes: 0
Views: 557
Reputation: 1832
If it's your project's dependency (and you import this dependency into your app but you have a control over the dependency) it makes sense to declare a bean with conditions. F.e.:
@Bean
@ConditionalOnMissingBean(SystemConfiguration.class) // mock bean in tests would be of the the same type so this one is skipped
SystemConfiguration systemConfiguration() {
return new SystemConfigurationImpl();
}
If you don't have a control over the dependency and you need the test bean it's natural to run tests with test
profile, so you can play with @Profile("test")
and @ActiveProfiles("test")
.
Good examples here: Spring Profiles
Upvotes: 1