In our application some beans are created for invoking third part service. Sometime we don't expect to or can't create these beans in @SpringBootTest context. I hope we can create mock to replace these beans more easier.
Like for instant, I defined an s3Service bean in my @Configuration class
@Configuration
public class S3Configuration {
@Bean
public S3Service s3Service() {
// ....
}
}
What I want is I can defined a mock bean to replace it in my @TestConfiguration class
@TestConfiguration
public class S3ServiceMockConfig {
@Bean
public S3Service s3Service() {
return mock(S3Service.class);
}
}
Currently, we can't do that, when spring find out two beans with same type and name, it will throw exception.
Although I can change the name of the mock bean and mark it as @Primary, but it doesn't work for those injections that use @Qualifier.
The another way is to conditional create these beans.
@Configuration
public class S3Configuration {
@ConditionalOnProperty(name = "runtime_unit_test", havingValue = "false")
@Bean
public S3Service s3Service() {
// ....
}
}
But It doesn't make sense to write my production code like this for a testing purpose.
Best regards
Comment From: snicoll
Have you tried @MockBean?