【问题标题】:How to test @Configuration and @Bean in a Spring Boot Application?如何在 Spring Boot 应用程序中测试 @Configuration 和 @Bean?
【发布时间】:2022-01-13 03:46:04
【问题描述】:

我是 Spring Boot 的新手。我需要为下面的类编写 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));
    }
}

有人可以帮忙吗?感谢您的宝贵时间。

【问题讨论】:

    标签: java spring spring-boot junit


    【解决方案1】:

    您可以使用 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));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-25
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 2016-10-20
      • 2023-03-10
      • 2019-01-18
      • 2016-04-05
      • 1970-01-01
      相关资源
      最近更新 更多