jersey2 Unit testing,HttpServletRequest is null












3















Ask everybody to help?



jersey Bug connection: [1]: https://java.net/jira/browse/JERSEY-2412



The servlet request, response and context not injected into the class when I using test provider (tested jetty and grizzly2).
I using packages annotation to pull up the application.





Do you have any other way?





 public class VMResourceTest extends BaseTest {  

@Test
public void testCreateVm() {

String bodyData = loadClassPathData(CLASS_PATH+File.separator+"tools"+File.separator+"createVm.json");
Response response = target("/tool/cloud/vrm/fm/ghca_vms").queryParam("platform_id", "A22A4B0C3AEC49F5916EA8CC01F56E9A")
.request().header("X-Auth-GHCA-User-ID", "X-Auth-GHCA-User-ID")
.post(Entity.entity(bodyData, MediaType.APPLICATION_JSON));
assertEquals("200", response.getStatus());
}
}




    public class BaseTest extends JerseyTest{  
public String CLASS_PATH = "classpath:";
public WebTarget target;
public Client client;

@Override
protected Application configure() {
enable(TestProperties.LOG_TRAFFIC);
enable(TestProperties.DUMP_ENTITY);
ResourceConfig rc = new ResourceConfig().packages("com.ghca.easyview.server.api.resource");
rc.register(SpringLifecycleListener.class);
rc.register(RequestContextListener.class);

rc.property("contextConfigLocation", "classpath:spring/spring-config.xml");
return rc;
}



public String loadClassPathData(String classFilePath){
File schemaContextFile = null;
String result = "";
try {
schemaContextFile = readSchemaFile(classFilePath);
BufferedReader br = new BufferedReader(new FileReader(schemaContextFile));
String s = null;
while((s = br.readLine())!=null){
result = result + "n" +s;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}




    @Component  
@Path("tool/cloud/vrm")
public class VMResource extends BaseResource{

@Autowired
private VMService vmService;

@Context
public HttpServletRequest request;
@Context
public HttpServletResponse response;


@POST
@Path("{platform_type}/ghca_vms")
@Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
public Response createVm(@PathParam("platform_type") String platformType,
@QueryParam("platform_id") String platformId) {}


request and response is null.










share|improve this question





























    3















    Ask everybody to help?



    jersey Bug connection: [1]: https://java.net/jira/browse/JERSEY-2412



    The servlet request, response and context not injected into the class when I using test provider (tested jetty and grizzly2).
    I using packages annotation to pull up the application.





    Do you have any other way?





     public class VMResourceTest extends BaseTest {  

    @Test
    public void testCreateVm() {

    String bodyData = loadClassPathData(CLASS_PATH+File.separator+"tools"+File.separator+"createVm.json");
    Response response = target("/tool/cloud/vrm/fm/ghca_vms").queryParam("platform_id", "A22A4B0C3AEC49F5916EA8CC01F56E9A")
    .request().header("X-Auth-GHCA-User-ID", "X-Auth-GHCA-User-ID")
    .post(Entity.entity(bodyData, MediaType.APPLICATION_JSON));
    assertEquals("200", response.getStatus());
    }
    }




        public class BaseTest extends JerseyTest{  
    public String CLASS_PATH = "classpath:";
    public WebTarget target;
    public Client client;

    @Override
    protected Application configure() {
    enable(TestProperties.LOG_TRAFFIC);
    enable(TestProperties.DUMP_ENTITY);
    ResourceConfig rc = new ResourceConfig().packages("com.ghca.easyview.server.api.resource");
    rc.register(SpringLifecycleListener.class);
    rc.register(RequestContextListener.class);

    rc.property("contextConfigLocation", "classpath:spring/spring-config.xml");
    return rc;
    }



    public String loadClassPathData(String classFilePath){
    File schemaContextFile = null;
    String result = "";
    try {
    schemaContextFile = readSchemaFile(classFilePath);
    BufferedReader br = new BufferedReader(new FileReader(schemaContextFile));
    String s = null;
    while((s = br.readLine())!=null){
    result = result + "n" +s;
    }
    br.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return result;
    }
    }




        @Component  
    @Path("tool/cloud/vrm")
    public class VMResource extends BaseResource{

    @Autowired
    private VMService vmService;

    @Context
    public HttpServletRequest request;
    @Context
    public HttpServletResponse response;


    @POST
    @Path("{platform_type}/ghca_vms")
    @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public Response createVm(@PathParam("platform_type") String platformType,
    @QueryParam("platform_id") String platformId) {}


    request and response is null.










    share|improve this question



























      3












      3








      3








      Ask everybody to help?



      jersey Bug connection: [1]: https://java.net/jira/browse/JERSEY-2412



      The servlet request, response and context not injected into the class when I using test provider (tested jetty and grizzly2).
      I using packages annotation to pull up the application.





      Do you have any other way?





       public class VMResourceTest extends BaseTest {  

      @Test
      public void testCreateVm() {

      String bodyData = loadClassPathData(CLASS_PATH+File.separator+"tools"+File.separator+"createVm.json");
      Response response = target("/tool/cloud/vrm/fm/ghca_vms").queryParam("platform_id", "A22A4B0C3AEC49F5916EA8CC01F56E9A")
      .request().header("X-Auth-GHCA-User-ID", "X-Auth-GHCA-User-ID")
      .post(Entity.entity(bodyData, MediaType.APPLICATION_JSON));
      assertEquals("200", response.getStatus());
      }
      }




          public class BaseTest extends JerseyTest{  
      public String CLASS_PATH = "classpath:";
      public WebTarget target;
      public Client client;

      @Override
      protected Application configure() {
      enable(TestProperties.LOG_TRAFFIC);
      enable(TestProperties.DUMP_ENTITY);
      ResourceConfig rc = new ResourceConfig().packages("com.ghca.easyview.server.api.resource");
      rc.register(SpringLifecycleListener.class);
      rc.register(RequestContextListener.class);

      rc.property("contextConfigLocation", "classpath:spring/spring-config.xml");
      return rc;
      }



      public String loadClassPathData(String classFilePath){
      File schemaContextFile = null;
      String result = "";
      try {
      schemaContextFile = readSchemaFile(classFilePath);
      BufferedReader br = new BufferedReader(new FileReader(schemaContextFile));
      String s = null;
      while((s = br.readLine())!=null){
      result = result + "n" +s;
      }
      br.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      return result;
      }
      }




          @Component  
      @Path("tool/cloud/vrm")
      public class VMResource extends BaseResource{

      @Autowired
      private VMService vmService;

      @Context
      public HttpServletRequest request;
      @Context
      public HttpServletResponse response;


      @POST
      @Path("{platform_type}/ghca_vms")
      @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
      @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
      public Response createVm(@PathParam("platform_type") String platformType,
      @QueryParam("platform_id") String platformId) {}


      request and response is null.










      share|improve this question
















      Ask everybody to help?



      jersey Bug connection: [1]: https://java.net/jira/browse/JERSEY-2412



      The servlet request, response and context not injected into the class when I using test provider (tested jetty and grizzly2).
      I using packages annotation to pull up the application.





      Do you have any other way?





       public class VMResourceTest extends BaseTest {  

      @Test
      public void testCreateVm() {

      String bodyData = loadClassPathData(CLASS_PATH+File.separator+"tools"+File.separator+"createVm.json");
      Response response = target("/tool/cloud/vrm/fm/ghca_vms").queryParam("platform_id", "A22A4B0C3AEC49F5916EA8CC01F56E9A")
      .request().header("X-Auth-GHCA-User-ID", "X-Auth-GHCA-User-ID")
      .post(Entity.entity(bodyData, MediaType.APPLICATION_JSON));
      assertEquals("200", response.getStatus());
      }
      }




          public class BaseTest extends JerseyTest{  
      public String CLASS_PATH = "classpath:";
      public WebTarget target;
      public Client client;

      @Override
      protected Application configure() {
      enable(TestProperties.LOG_TRAFFIC);
      enable(TestProperties.DUMP_ENTITY);
      ResourceConfig rc = new ResourceConfig().packages("com.ghca.easyview.server.api.resource");
      rc.register(SpringLifecycleListener.class);
      rc.register(RequestContextListener.class);

      rc.property("contextConfigLocation", "classpath:spring/spring-config.xml");
      return rc;
      }



      public String loadClassPathData(String classFilePath){
      File schemaContextFile = null;
      String result = "";
      try {
      schemaContextFile = readSchemaFile(classFilePath);
      BufferedReader br = new BufferedReader(new FileReader(schemaContextFile));
      String s = null;
      while((s = br.readLine())!=null){
      result = result + "n" +s;
      }
      br.close();
      } catch (IOException e) {
      e.printStackTrace();
      }
      return result;
      }
      }




          @Component  
      @Path("tool/cloud/vrm")
      public class VMResource extends BaseResource{

      @Autowired
      private VMService vmService;

      @Context
      public HttpServletRequest request;
      @Context
      public HttpServletResponse response;


      @POST
      @Path("{platform_type}/ghca_vms")
      @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
      @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
      public Response createVm(@PathParam("platform_type") String platformType,
      @QueryParam("platform_id") String platformId) {}


      request and response is null.







      java rest jersey






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Apr 1 '15 at 8:55







      jack

















      asked Apr 1 '15 at 8:42









      jackjack

      5719




      5719
























          1 Answer
          1






          active

          oldest

          votes


















          5














          You need to configure the JerseyTest for a Servlet environment. In your JerseyTest, you should have something like



          @Override
          protected TestContainerFactory getTestContainerFactory() {
          return new GrizzlyWebTestContainerFactory();
          }

          @Override
          protected DeploymentContext configureDeployment() {
          ResourceConfig config = new ResourceConfig(SessionResource.class);
          return ServletDeploymentContext.forServlet(
          new ServletContainer(config)).build();
          }


          If you look at the ServletDeploymentContext.forServlet, it returns a ServletDeploymentContext.Builder. If you look at the Javadoc, you will see some familiar looking methods, like initParam(...,...), addListener, etc. This is just like building your web.xml programmatically. Just keep chaining methods, then build.



          With the above configuration, you no longer need to override the configure method in the JerseyTest. Just add the ResourceConfig like seen above.



          See other test examples here



          Also See related:




          • How to in-memory unit test Spring-Jersey






          share|improve this answer


























          • hi peeskillet thanks,i question solve,

            – jack
            Apr 1 '15 at 9:52











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29386360%2fjersey2-unit-testing-httpservletrequest-is-null%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          5














          You need to configure the JerseyTest for a Servlet environment. In your JerseyTest, you should have something like



          @Override
          protected TestContainerFactory getTestContainerFactory() {
          return new GrizzlyWebTestContainerFactory();
          }

          @Override
          protected DeploymentContext configureDeployment() {
          ResourceConfig config = new ResourceConfig(SessionResource.class);
          return ServletDeploymentContext.forServlet(
          new ServletContainer(config)).build();
          }


          If you look at the ServletDeploymentContext.forServlet, it returns a ServletDeploymentContext.Builder. If you look at the Javadoc, you will see some familiar looking methods, like initParam(...,...), addListener, etc. This is just like building your web.xml programmatically. Just keep chaining methods, then build.



          With the above configuration, you no longer need to override the configure method in the JerseyTest. Just add the ResourceConfig like seen above.



          See other test examples here



          Also See related:




          • How to in-memory unit test Spring-Jersey






          share|improve this answer


























          • hi peeskillet thanks,i question solve,

            – jack
            Apr 1 '15 at 9:52
















          5














          You need to configure the JerseyTest for a Servlet environment. In your JerseyTest, you should have something like



          @Override
          protected TestContainerFactory getTestContainerFactory() {
          return new GrizzlyWebTestContainerFactory();
          }

          @Override
          protected DeploymentContext configureDeployment() {
          ResourceConfig config = new ResourceConfig(SessionResource.class);
          return ServletDeploymentContext.forServlet(
          new ServletContainer(config)).build();
          }


          If you look at the ServletDeploymentContext.forServlet, it returns a ServletDeploymentContext.Builder. If you look at the Javadoc, you will see some familiar looking methods, like initParam(...,...), addListener, etc. This is just like building your web.xml programmatically. Just keep chaining methods, then build.



          With the above configuration, you no longer need to override the configure method in the JerseyTest. Just add the ResourceConfig like seen above.



          See other test examples here



          Also See related:




          • How to in-memory unit test Spring-Jersey






          share|improve this answer


























          • hi peeskillet thanks,i question solve,

            – jack
            Apr 1 '15 at 9:52














          5












          5








          5







          You need to configure the JerseyTest for a Servlet environment. In your JerseyTest, you should have something like



          @Override
          protected TestContainerFactory getTestContainerFactory() {
          return new GrizzlyWebTestContainerFactory();
          }

          @Override
          protected DeploymentContext configureDeployment() {
          ResourceConfig config = new ResourceConfig(SessionResource.class);
          return ServletDeploymentContext.forServlet(
          new ServletContainer(config)).build();
          }


          If you look at the ServletDeploymentContext.forServlet, it returns a ServletDeploymentContext.Builder. If you look at the Javadoc, you will see some familiar looking methods, like initParam(...,...), addListener, etc. This is just like building your web.xml programmatically. Just keep chaining methods, then build.



          With the above configuration, you no longer need to override the configure method in the JerseyTest. Just add the ResourceConfig like seen above.



          See other test examples here



          Also See related:




          • How to in-memory unit test Spring-Jersey






          share|improve this answer















          You need to configure the JerseyTest for a Servlet environment. In your JerseyTest, you should have something like



          @Override
          protected TestContainerFactory getTestContainerFactory() {
          return new GrizzlyWebTestContainerFactory();
          }

          @Override
          protected DeploymentContext configureDeployment() {
          ResourceConfig config = new ResourceConfig(SessionResource.class);
          return ServletDeploymentContext.forServlet(
          new ServletContainer(config)).build();
          }


          If you look at the ServletDeploymentContext.forServlet, it returns a ServletDeploymentContext.Builder. If you look at the Javadoc, you will see some familiar looking methods, like initParam(...,...), addListener, etc. This is just like building your web.xml programmatically. Just keep chaining methods, then build.



          With the above configuration, you no longer need to override the configure method in the JerseyTest. Just add the ResourceConfig like seen above.



          See other test examples here



          Also See related:




          • How to in-memory unit test Spring-Jersey







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 23 '17 at 12:32









          Community

          11




          11










          answered Apr 1 '15 at 9:29









          Paul SamsothaPaul Samsotha

          151k20291481




          151k20291481













          • hi peeskillet thanks,i question solve,

            – jack
            Apr 1 '15 at 9:52



















          • hi peeskillet thanks,i question solve,

            – jack
            Apr 1 '15 at 9:52

















          hi peeskillet thanks,i question solve,

          – jack
          Apr 1 '15 at 9:52





          hi peeskillet thanks,i question solve,

          – jack
          Apr 1 '15 at 9:52




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29386360%2fjersey2-unit-testing-httpservletrequest-is-null%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          mysqli_query(): Empty query in /home/lucindabrummitt/public_html/blog/wp-includes/wp-db.php on line 1924

          How to change which sound is reproduced for terminal bell?

          Can I use Tabulator js library in my java Spring + Thymeleaf project?