mikeshi
mikeshi

Reputation: 63

how can I specify the unit test when I use spring conditional bean

I created a spring boot project where I defined some conditional beans, which use the ConditionalOnProperty annotation. So, according to my properties file settings, some bean will be created, and some not (Because I have some back-ends for one thing, it can be set in properties file to choose one when in production situation).

But I wrote the unit tests for all beans, so the unit tests will not be success because in some cases, some beans will not be created at all, and I will get the UnsatisfiedDependencyException.

Is there any way that I can only test the created bean, I tried to add ConditionalOnProperty annotation on unit test method, but it does not work since it is about bean registration.

If there is not any good solution, I will split the project into some libs for every back-end, but it is just a small project.

Upvotes: 0

Views: 2158

Answers (1)

mikeshi
mikeshi

Reputation: 63

OK, finally I found the way.

In my test case, I use Autowired annotation, firstly, I should add

 required = false 
parameter for Autowired, so when the bean is not created because ConditionOnProperty is not met, it will not throw a NoSuchBeanException, and the field keeps null.

Secondly, I should use JUnit's Assume class to check whether the condition is met, if condition is not met, the case will be ignored.

Because my condition is the value in the properties file, I read it and use it to feed assumeTrue method.

Maybe there is another better way, but it works for me.

Upvotes: 1

Related Questions