title: RestEasy Mock unit test with CDI
body: <p>I've a simple RestEasy WebServie which will take a dependency.</p>
  
  <p>When I test by publishing into Wildfly server everything is working fine. But I tried to mock it using JUnit. But, it's throwing <code>null pointer exception</code> as the dependency isn't injected.</p>
  
  <p>Following is the code which I've done. What is wrong I'm doing.</p>
  
  <p><strong>WebService;</strong></p>
  
  <pre><code>import javax.inject.Inject;
  import javax.ws.rs.GET;
  import javax.ws.rs.Path;
  import javax.ws.rs.core.MediaType;
  import javax.ws.rs.core.Response;
  
  @Path("/")
  public class IlService {
  
      @Inject
      private il.helper.RequestData rData;
  
      @GET
      public Response postIds() {
  
          return Response.status( 200 ).type( MediaType.TEXT_HTML ).entity( rData.getRequestData().get( "logicalOperator" ).asText() ).build();
      }
  }
  </code></pre>
  
  <p><strong>JUnit Test class:</strong></p>
  
  <pre><code>import org.jboss.resteasy.core.Dispatcher;
  import org.jboss.resteasy.mock.MockDispatcherFactory;
  import org.jboss.resteasy.mock.MockHttpRequest;
  import org.jboss.resteasy.mock.MockHttpResponse;
  import org.jboss.resteasy.spi.InjectorFactory;
  import org.jboss.resteasy.spi.PropertyInjector;
  import org.jboss.resteasy.spi.Registry;
  import org.jboss.resteasy.spi.ResourceFactory;
  import org.jboss.resteasy.spi.ResteasyProviderFactory;
  import org.junit.Before;
  import org.junit.Test;
  
  import il.helper.RequestData;
  import il.services.IlService;
  import junit.framework.Assert;
  
  public class IlServiceTest {
  
      private Dispatcher      dispatcher;
      ResteasyProviderFactory resteasyProviderFactory;
      ResourceFactory         factory;
      InjectorFactory         injectorFactory;
      PropertyInjector        propertyInjector;
  
      @Before
      public void setUpResource() {
  
          dispatcher = MockDispatcherFactory.createDispatcher();
          resteasyProviderFactory = dispatcher.getProviderFactory();
          injectorFactory = resteasyProviderFactory.getInjectorFactory();
          propertyInjector = injectorFactory.createPropertyInjector( IlService.class, resteasyProviderFactory );
          propertyInjector.inject( new RequestData() );
          resteasyProviderFactory.setInjectorFactory( injectorFactory );
          Registry registry = dispatcher.getRegistry();
          registry.addSingletonResource( new IlService() );
      }
  
      @Test
      public void IlServicePost() {
  
          try {
              MockHttpRequest request = MockHttpRequest.create( "get", "" );
              MockHttpResponse response = new MockHttpResponse();
  
              dispatcher.invoke( request, response );
  
              Assert.assertEquals( 200, response.getStatus() );
          } catch ( Exception e ) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>