Inject null to autowired @Resource member in spring unit test
I have implemented some unit tests which use the Spring Test Framework. The tests include members that get autowired by name, e.g.
@Resource
private FooBar myFooBar;
I configured my test to be able to run with different configurations like mentioned here.
Some configurations do not allow to run all tests (e.g. no database available). I want to skip the test in this case. My criteria to skip the test is myFooBar == null
.
assumeTrue(myFooBar != null)
I am facing the problem how to inject null
into this member. I tried
<bean id="myFooBar" class="FooBar">
<null />
</bean>
But this does not work (Invalid content was found starting with element 'null'...)
If I do not configure the bean in my context.xml I get a NoSuchBeanDefinitionException
.
Can't be that hard for Spring to just inject null
to my member - but it's definitly hard for me :-)
I have to add that my FooBar
class has no defa开发者_开发问答ult constructor.
Do you have any idea of how to inject null
or how to ignore missing bean definitions on autowired test class members?
Regards
K. ClaszenIf You would autowire by type using @Autowired
instead of autowiring by name with @Resource
then You could do:
@Autowired(required = false)
private FooBar myFooBar;
Setting required = false
will make Spring ignore this dependency if it cannot be resolved, as the documentation states.
You can still use autowiring by name with @Autowired
using the @Qualifier
to provide the bean name:
@Autowired(required = false)
@Qualifier("myFooBar")
private FooBar myFooBar;
For more info on @Qualifier
see this reference page.
精彩评论