Monday, March 23, 2015

Testing JEE6 CDI outside of Container using Weld-SE

0. Add the dependencies in Maven Model

1. Develop the Class(es) which are annotated with CDI
 public class ContextsDependencyInjectionManager {  
      private static final Logger LOGGER = Logger.getLogger(ContextsDependencyInjectionManager.class);  
      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.
                     .fire(new EngagementAttributeChangedEvent(  
                               "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: