views:

291

answers:

2

Hi,

Is it possible to JUnit test if wiring by Spring is succesfully?

I would like to do this by reflection. Like: get all beans with id *Controller and test if the fields *services are not null?

Thank you!

+1  A: 
  • build your ApplicationContext either via XmlWebApplicationContext's constructor or via the spring JUnit test runner and make your test implement ApplicationContextAware

  • use the methods of ApplicationContext to find and verify everything you need, with the help of ReflectionUtils and ReflectionTestUtils. But have in mind that if injection fails, the whole context initialization fails.

Bozho
+3  A: 

A better way is to annotate the setter methods with org.springframework.beans.factory.annotation.Required, and add the required annotations post processor:

<!--
    This bean will cause an error if you forget to supply any properties
    annotated with @Required on the setter method; this is good for
    catching errors.
-->
<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

If you want to verify that methods that match a certain pattern have the @Required annotation, implement a compiler hook, an AnnotationProcessor, that causes a compiler failure if methods matching a certain pattern aren't annotated with @Required.

LES2