What is the best way to write a test case for JERS

2019-03-18 12:31发布

问题:

I have a JAX-RS web service implemented with Jersey library and now I want to test it. In order to do that I'd like to host this service in my test by preinitializing it with mocked services.

What is the best way to host such a service and execute the test calls?

@Path("/srv")
public class MyService
{
   @GET
   public void action(@Context UriInfo uri)
   { ... }
}

@Test
public void myTest()
{
   MyService service = new MyService();
   service.setSomething(...);

   // How do I host it?

   // How do I call it?
}

回答1:

The new (revised) Jersey Test Framework which is part of the Jersey 1.1.2-ea release now supports the In-Process or In-Memory testing. In order to run your tests in-memory all you have to do is set the property test.containerFactory to com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory, i.e., run your tests as follows:

mvn clean test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory -DenableLogging

For more details please go through the blog entry titled Jersey Test Framework re-visited! at http://blogs.oracle.com/naresh.



回答2:

I believe the Jersey Test Framework provides a solution for your requirement. It allows you to deploy a single service, and run all its tests. You could use the framework to run your tests against Grizzly Web Container, Embedded GlassFish and/or HTTPServer.

Please note that you could use the framework to run your tests against the regular web containers like GlassFish and Tomcat too. In case you have any more queries please feel free to send me or the Jersey users mailing list - users@jersey.dev.java.net an e-mail.



回答3:

I haven't tried it, but a JUnit extension like HtmlUnit or HttpUnit may be a good way to test a JAX-RS/Jersey service. The test case can use XPaths to find expected return values and validate the returned value against the expected. See: http://htmlunit.sourceforge.net/gettingStarted.html for more info.



回答4:

You can use Grizzly to host the services and then use the Jersey Client to access them. Take a look at the sample applications. For example, in the Bookstore sample you may find the TestSupport class and JerseyTest class (found in the jersey-test-framework) of particular interest.

I hope this helps.

(Unfortunately Stack Overflow wouldn't let me post until I removed all the hyperlinks so happy Googling!).



回答5:

Okay I get it now. Right now the framework doesn't support IN PROCESS, bt we are working on it. We will see that this support would be added in a coming version of the Jersey Test Framework



回答6:

Have you looked in to using the Jersey Test Framework? Unfortunately it's still more integration test than unit test, but it might get you on your way.