Reputation: 2754
I'm new to Spring Boot. I need to write JUnit test cases for the below class. What is the efficient way to write a unit test case for @Configuration and @Bean annotation?
@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));
}
}
Can some one help? Thank you for your time.
Upvotes: 2
Views: 9610
Reputation: 161
You can do it by using ContextConfiguration and injecting ApplicationContext or injecting directly your beans @Autowired AWSCredentialsProvider awsCredentials as properties. Example below uses ApplicationContext directly.
@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));
}
}
Upvotes: 3