Monday, March 23, 2015

Testing JEE6 CDI outside of Container using Weld-SE

0. Add the dependencies in Maven Model
    <dependency>  
       <groupId>org.jboss.weld.se</groupId>  
       <artifactId>weld-se-core</artifactId>  
       <version>2.2.9.Final</version>  
       <scope>test</scope>  
    </dependency>  

1. Develop the Class(es) which are annotated with CDI
 @ApplicationScoped  
 public class ContextsDependencyInjectionManager {  
      private static final Logger LOGGER = Logger.getLogger(ContextsDependencyInjectionManager.class);  
      @Resource  
      private ManagedThreadFactory managedThreadFactory;  
      @Inject @Persistent
      private EngagementManager persistentManger;  
      @Inject @Radia
      private EngagementManager radiaManager;  
      @Inject @Accelerite  
      private EngagementManager acceleritManager;  
      @Inject @Services  
      private EngagementManager servicesManager;  

      ... // add functionality, methods, other atrributes
}

2. Write a Test Case to test the Class(es) using Weld-SE
 public class ContextsDependencyInjectionManagerTest {  
      public static void main(String[] args) throws Exception {  
           ContextsDependencyInjectionManagerTest test = new ContextsDependencyInjectionManagerTest();  
           
           // cdi initialization outside of container  
           Weld weld = new Weld();  
           WeldContainer weldContainer = weld.initialize();  
           ContextsDependencyInjectionManager cdiManager = weldContainer.instance()  
                     .select(ContextsDependencyInjectionManager .class).get();  
      
           ... // other tests, fire events, assert
}

3.Using/Firing Events in Weld-SE - Test @Observes
If you have used the observer pattern or added listeners using @Observes, you may choose to test them out as follows.
           weldContainer  
                     .event()  
                     .select(EngagementAttributeChangedEvent.class)  
                     .fire(new EngagementAttributeChangedEvent(  
                               EngagementManagerConstants.ENGAGEMENT_MANAGER_ENTITY_DASHBOARD,  
                               "contact", "sumith_puri", "pl"));  

This is helpful for the initial developer testing and before a version is available to deploy in the container, to understand if all dependencies are getting injected and whether many of the CDI annotations are working as intended.

No comments: