0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Another way to do it is to use the same @Autowired(required = false) with @ConditionalOnBean(<not autowired bean class>) on the required tests. Then you don't depend on the configuration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.