4

I got a jax-rs resource

@Path("rest/v1/serviceemail")
public class PreviewResource implements Preview
{  
  @EJB
  private Mapper mapper;

I'm creating an IT test with jersey-test-framework-core and jersey-test-framework-grizzly2.

When I launch the test the ejb is not injected in the service and so I receive a NPE.

Massimo Ugues
  • 4,373
  • 8
  • 43
  • 56
  • Mock the `Mapper`. Unless you need a full integration test, then you need something that can load a full EE environment. Maybe like arquillian. – Paul Samsotha Sep 15 '15 at 08:36
  • You can see one way [here](http://stackoverflow.com/a/27447345/2587435) of mocking the `Mapper` using Mockito – Paul Samsotha Sep 15 '15 at 08:44
  • I was thinking about an Integration Test because the unit test is already done; so I would like to use a light EE embedded container. – Massimo Ugues Sep 15 '15 at 09:29
  • I would check out arquillian. That is actually the only one I know, so I can't really suggest any others. – Paul Samsotha Sep 15 '15 at 09:40

1 Answers1

1

I found a solution by implementing a custom InjectableProvider. The following code is taken from an Oracle article:

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.ext.Provider;

import com.sun.jersey.core.spi.component.ComponentContext;
import com.sun.jersey.core.spi.component.ComponentScope;
import com.sun.jersey.spi.inject.Injectable;
import com.sun.jersey.spi.inject.InjectableProvider;

@Provider
public class EJBProvider implements InjectableProvider<EJB, Type> {

    public Scope getScope() {
        return Scope.Singleton;
    }

    public Injectable getInjectable(ComponentContext cc, EJB ejb, Type t) {
        if (!(t instanceof Class)) return null;

        try {
            Class c = (Class)t;        
            Context ic = new InitialContext();

            final Object o = ic.lookup(c.getName());

            return new Injectable<Object>() {
                public Object getValue(HttpContext c) {
                    return o;
                }                    
            };            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

I had to slightly adapt it to fit my environment. Also note that the provider has to be in the same package as your service class, otherwise it won't be picked up (it does not say that in the article).

Adrian B.
  • 4,333
  • 1
  • 24
  • 38