1 Reply Latest reply on May 12, 2011 11:39 AM by qtrin

    Re: Use @EJB in helper class

    magnus.smith

      You could use a service provider framework to register ejbs in the main TestClass and then retrieve them in your helper classes.

       

      In your Test class you could inject your ejb

       

      @EJB

      private MyService myService;

       

      Then in a method that is called before your tests

       

      private void init() {

              // add references to the injected ejbs for use by test helper classes

              ServiceConfig.INSTANCE.addService(myService);

      }

       

      Then in you test helper class you can retrieve the ejb like this

       

      public class TestHelper {

            private MyService myService;

       

          public TestHelper() {

              myService = ServiceConfig.INSTANCE.getService(MyService.class);

          }

       

        .....

      }

       

      To use the ServiceConfig - you just need to mark your ejb as implementing BaseService

       

      public interface BaseService {

      }

       

       

      /**

      * Acts as a holder for injected stateless EJBs so that they can be accessed

      * outside of their normal context.

      *

      * @author Magnus.Smith

      */

      public enum ServiceConfig {

       

          INSTANCE;

       

          private Set<BaseService> services = new HashSet<BaseService>();

       

          /**

           * Gets the service keyed by serviceClass.

           *

           * @param serviceClazz The serviceClass to retrieve

           * @return service matching given class

           * @throws IllegalArgumentException if service not present

           */

          public <E> E getService(Class<E> serviceClazz) throws IllegalArgumentException {

              for (BaseService base : services) {

                  if (serviceClazz.isAssignableFrom(base.getClass())) {

                      return (E) base;

                  }

              }

              // service not present

              throw new IllegalArgumentException(String.format(

                      "The service %s is not present in config!", serviceClazz.getName()));

          }

       

          /**

           * Adds the ejb to

           * @param service

           */

          public void addService(BaseService service) {

              services.add(service);

          }

      }