[英]How to test Spring boot application configuration class with dependency injection of map?
[英]How to test @Configuration and @Bean in a Spring Boot Application?
我是 Spring 引导的新手。 我需要为下面的 class 编写 JUnit 测试用例。 为@Configuration 和@Bean 注解编写单元测试用例的有效方法是什么?
@Configuration
public class ABCConfig {
@Autowired
private AwsApplicationProperties AwsApplicationProperties;
List<AmazonSNS> amazonSNSClientArray = new ArrayList<>();
@Bean
public List<AmazonSNS> amazonSnsClient() {
//some code here
}
@Bean
public AWSCredentialsProvider aWSCredentials(String awsAccessKeyId, String awsSecretKeyId) {
return new AWSStaticCredentialsProvider(new BasicAWSCredentials(awsAccessKeyId, awsSecretKeyId));
}
}
有人可以帮忙吗? 感谢您的时间。
您可以使用 ContextConfiguration 并注入 ApplicationContext 或直接注入您的 bean @Autowired AWSCredentialsProvider awsCredentials 作为属性。 下面的示例直接使用 ApplicationContext。
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = { ABCConfig.class })
class ABCConfigUnitTest {
@Autowired
ApplicationContext context;
@Test
void givenImportedBeans_whenGettingEach_shallFindIt() {
assertThatBeanExists("aWSCredentials", AWSCredentialsProvider.class);
}
private void assertThatBeanExists(String beanName, Class<?> beanClass) {
Assertions.assertTrue(context.containsBean(beanName));
Assertions.assertNotNull(context.getBean(beanClass));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.