Jersey Test Framework re-visited!
One of the previous entries introduced the Jersey Test Framework, which has since been adopted and used by a good number of developers. However, there has been some feedback suggesting ways for making the framework a better one.
Based on all this feedback, we have worked on making some changes in the framework. With the release of Jersey 1.1.2-ea, we have this new version of the framework which is better than the previous version in the following ways:
- Introduced the concept of test container factories
- Various test container types, defined by the different test container factory implementations
- Support for the new In-Memory or In-Process test container
- Loosely-coupled with the test container factory implementations
- Loose coupling allows the definition and pluggability of custom test container factory implementations
- Support for running tests on an application pre-deployed on an external container
But, there have been some major changes in the API, which seemed obvious for the cause.
This entry will describe what are the API changes, and how an user test can be defined, etc.
Breaking changes from 1.1.1-ea to 1.1.2-ea
- The maven project groupId has changed from “com.sun.jersey.test.framework” to “com.sun.jersey”.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-test-framework</artifactId>
<version>1.1.2-ea</version>
<dependency>
- The extending of Jersey unit test and configuration has changed.
The test class has to just pass an instance of AppDescriptor. For instance, the constructor of the spring-annotations sample test, passes this information as follows:
public SpringAnnotationsWebAppTest() throws Exception {
super(new WebAppDescriptor.Builder("com.sun.jersey.samples.springannotations.resources.jerseymanaged")
.contextPath("spring")
.contextParam("contextConfigLocation", "classpath:applicationContext.xml")
.servletClass(SpringServlet.class)
.contextListenerClass(ContextLoaderListener.class)
.build());
}
Note the use of the Builder design pattern, which makes it really easy to define an instance of the AppDescriptor while defining all the application attributes.
- The test container type with which to run the tests has to be specified using the System Property test.containerFactory. Note that it used to be container.type till the previous version.
- Unlike the previous implementation, the test container type value is not a string which maps to the container type, but the fully qualified class name of the test container factory is passed as value for the property test.containerFactory.
mvn test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.grizzly.web.GrizzlyWebTestContainerFactory
About the AppDescriptor
AppDescriptor is an abstract class which is extended by two classes - the LowLevelAppDescriptor and the WebAppDescriptor. These classes allow the definition of the various attributes of the application - like its context-path, url-pattern, root resource classes or packages, etc. While the LowLevelAppDescriptor can be used is cases were tests are to be run on light-weight containers like Grizzly or HTTPServer, the WebAppDescriptor is used in cases where tests could be run on the web-based containers like EmbeddedGlassFish, Grizzly Web Container, and the light-weight containers as well*.
Test Container Factories
The test framework comes with a set of test container factory implementations which are responsible for creating the test container(s).
The following low-level test container factories are provided:
GrizzlyTestContainerFactoryfor testing with the low-level Grizzly HTTP container.HTTPContainerFactoryfor testing with the Light Weight HTTP server distributed with Java SE 6.InMemoryTestContainerFactoryfor testing in memory without using underlying HTTP client and server side functionality to send requests and receive responses.
GrizzlyWebTestContainerFactoryfor testing with the Grizzly Web container and Servlet support.EmbeddedGlassFishTestContainerFactoryfor testing with embedded GlassFish.ExternalTestContainerFactoryfor testing when the Web application is independently deployed in a separate JVM to that of the tests. For example, the application may be deployed to the Glassfish v2 or v3 application server.
Running Tests using Maven
As previously said, the container on which the tests have to be run is specified using the system property test.containerFactory which holds the fully-qualified classname of the test container factory which creates an instance of the test container, i.e.,
mvn clean test -Dtest.containerFactory=<container-factory fully-qualified class name>
Note:
1. If tests are to be run on external container like GlassFish, the application has to be explicity deployed on the container before running the tests.
a. Package the application:
mvn clean package -Dmaven.test.skip=true
b. Deploy the generated application war file
c. Run the tests:
mvn test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.external.ExternalTestContainerFactory
2. If the tests are to be run on EmbeddedGlassFish, one additional property container.type has to be set along with test.containerFactory:
mvn clean test -Dtest.containerFactory=com.sun.jersey.test.framework.spi.container.embedded.glassfish.EmbeddedGlassFishTestContainerFactory -Dcontainer.type=EmbeddedGF
3. If the property test.containerFactory is not set, the tests would be run on the Grizzly Web container by default.
Enable Logging
The framework allows the logging of the HTTP requests and responses being sent over the wire during the test process. All that is needed to enable this logging is set the flag enableLogging.
mvn clean test -Dtest.containerFactory=<test container factory class> -DenableLogging
Programmatically setting the test container factory
The framework also allows setting the test container factory programmatically. This could be done by overriding the JerseyTest class's getTestContainerFactory method and returning the appropriate test container factory's instance. For example if Grizzly Web container has to be set as the default test container factory, it could be done as follows:
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
That's a brief description of the new version of the Jersey Test Framework. Please send an email to the Jersey user's mailing list users@jersey.dev.java.net in case you have any issues. Wish you a happy testing of your RESTful Web Services :)
There seems to be a problem with maven artifact "jersey-test-framework".
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-test-framework</artifactId>
<version>1.1.2-ea</version>
<dependency>
This does not download. Rest of the jersey jars download fine for 1.1.2-ea.
Posted by spulla on September 01, 2009 at 04:17 PM PDT #
Hi,
I'm able to use it without any issue.
The artifacts are available at the download.java.net site too -
http://download.java.net/maven/2/com/sun/jersey/jersey-test-framework/1.1.2-ea/
BTW, what repo are you using?
Do you have the following as one of the repositories:
<repository>
<id>m2.dev.java.net</id>
<url>http://download.java.net/maven/2</url>
<layout>default</layout>
</repository>
Posted by Naresh on September 02, 2009 at 01:22 AM PDT #
Hi Naresh,
Thanks for your response. I used the repo url you gave me. The good news is I was able download test framework but fails on org.glassfish.embedded:glassfish-embedded-all:jar:3.0-Prelude-Embedded-b14. (Transitive dependency).
Obviously I could download manually but I don't want to, for my scenario. I was writing some automated tests for my project so wanted to experiment with this version library.
sp
Posted by spulla on September 02, 2009 at 12:32 PM PDT #
Hi Naresh,
Ignore my previous comment. I got everything now. Thanks.
-sp
Posted by 128.102.248.100 on September 02, 2009 at 01:08 PM PDT #
Hi Spulla,
great to know that you got the framework working now.
Please feel free to send a mail to the users mailing list users@jersey.dev.java.net, in case you run into any issues.
Posted by Naresh on September 02, 2009 at 10:08 PM PDT #
I am using "GrizzlyWebTestContainerFactory (jersey-test-framework-1.1.2-ea.jar)" to write testcases for my jersey service which uses session variable.
I am not sure how to make available session objects through test framework?
Tried to set session objects using filterClass (WebAppDescriptor.Builder) but it shows me null pointer exception while starting container. I gone through the src code and found this chunk causing error:
try {
servletInstance = (Servlet) servletClass.newInstance();
} catch (InstantiationException ex) {
throw new TestContainerException(ex);
} catch (IllegalAccessException ex) {
It always excepting servletClass and when I setting filter class this code snippet sets this.servletClass = null and one more thing test framework not using filter class anywhere.
try {
servletInstance = (Servlet) servletClass.newInstance();
} catch (InstantiationException ex) {
throw new TestContainerException(ex);
} catch (IllegalAccessException ex) {public Builder filterClass(Class<? extends Filter> filterClass)
throws IllegalArgumentException {
if (filterClass == null)
throw new IllegalArgumentException("The filter class must not be null");
this.filterClass = filterClass;
this.servletClass = null;
return this;
}
Thanks,
Yogesh
Posted by Yogesh Kumar on September 12, 2009 at 01:53 AM PDT #
Hi Yogesh,
the framework not using the filter class was indeed a bug in the implementation, which I had overseen during the development. However, we have identified this after the release of 1.1.2-ea, and fixed it in 1.1.3-ea-SNAPSHOT. Can you please try using the 1.1.3-ea-SNAPSHOT version?
One more thing is, by design we have made the use of servlet or filter mutually exclusive.
Please let us know, if things are working for you with the current implementation or not.
Posted by Yogesh on September 12, 2009 at 10:50 AM PDT #
With 1.1.3-ea-SNAPSHOT version filter is getting executed but not forwarding request to requested resource.
My motivation to use filter here is to make available session objects to my jersey service layer.
Is there any other way to make available session objects to my jersey service through test framework?
Posted by 122.162.224.27 on September 12, 2009 at 12:44 PM PDT #
I'm using Jersey-RS 1.0 in netbeans 6.5 without maven.
I'm deploying to tomcat.
Any idea which jersey-test-framework version I should use?
Also, which grizzly jar file versions should I use with the given test framework version?
Thanks,
Brian
Posted by Brian on September 30, 2009 at 04:23 PM PDT #
Nevermind, I just made a maven project and and let it tell me the dependencies. Now I can drop them into my existing project.
Posted by Brian on September 30, 2009 at 08:23 PM PDT #
Great.
I hope you are using the latest version, i.e., 1.1.2-ea
Please let me know if you face any issues.
I shall soon add the links to the required jar files for non-maven users.
Posted by Naresh on September 30, 2009 at 11:56 PM PDT #
Any idea why I get this error?
java.lang.NoSuchMethodError: com.sun.grizzly.tcp.http11.GrizzlyAdapterChain.setDecodeUrl(Z)V
Using Jersey 1.0 that comes with NetBeans 6.5 plus the following jars:
grizzly-framework-1.9.8.jar
grizzly-http-1.9.8.jar
grizzly-http-servlet-1.9.8.jar
grizzly-portunif-1.9.8.jar
grizzly-rcm-1.9.8.jar
grizzly-servlet-webserver-1.9.8.jar
grizzly-utils-1.9.8.jar
jersey-test-framework-1.0.3.jar
Posted by Brian on October 01, 2009 at 07:05 AM PDT #
I just saw your other comment as well. So would 1.1.2-ea work with Jersey 1.0.3?
Posted by 24.124.29.17 on October 01, 2009 at 07:07 AM PDT #
First;
Is it possible to supply static resources (like html-files) to be served by the test web server along with the resources?
I have some 'not so clever' forwarding/redirects to static content in my rest resources that I need to test. But all I get is 404 on all the static resource I try to access. Everything works fine if I deploy the app.
simplfied resource;
@GET
public Response get() throws URISyntaxException {
return Response.temporaryRedirect(new URI("/index.html")).build();
}
Sounds like I missed something easy, or?
I'm using 1.1.3-ea, I need that filter fix namned above for my custom filters.
I've tried all of the containers (excluding ExternalTestContainerFactory which is no option and EmbeddedGlassFishTestContainerFactory which crashes hard)
And the seconds question;
Is it possible to serve jsp files (with custom Simple Tag Handler's) together with the resources aswell?
Posted by maq on October 01, 2009 at 07:31 AM PDT #
Brian,
that NoSuchMethodError indicates that its possibly because of multiple versions of Grizzly jars being present. Since, you are trying with JerseyTestFramework v 1.0.3, can you please use the Jersey jars of version 1.0.3 as well?
Coming to your other question of whether the test framework v1.1.2-ea would work with Jersey v1.0.3 - I doubt it would because the test framework has dependency on Jersey v1.1.2-ea. If you want to use the test framework v1.1.2-ea, you might want to consider upgrading to Jersey 1.1.2-ea (if its possible)?
I thought you were trying to run your tests on Tomcat. If its so, you will have to do the following for running the tests against Tomcat (an External Container Type, as per the framework's design):
1. Deploy your application on Tomcat.
2. If you are using JTF v1.0.3, set the property "container.type" to "External" while running the tests, and also set "JERSEY_HTTP_PORT" to your Tomcat instance's configured HTTP port, which usually would be "8080".
3. On the other hand if you are running the tests using JTF v1.1.2-ea, set the property "test.containerFactory" to "com.sun.jersey.test.framework.spi.container.external.ExternalTestContainerFactory", and also set "JERSEY_HTTP_PORT" according to your Tomcat configuration.
JTF --> Jersey Test Framework
Posted by Naresh on October 01, 2009 at 08:25 AM PDT #
Maq,
firstly, regarding the static HTML pages, currently the light-weight test containers like Grizzly or HTTPServer would not be able to do that, because all that the current implementation does is scan for resources using the configurations mentioned in the test. However, I think the EmbeddedGlassFish could be helpful in this case.
When you say, it crashes bad time, can you please let me know what really happens? May be a dump of the stack trace could be helpful (I'm assuming that in this case you had also set the property "container.type" to "EmbeddedGF", in addition to setting the "test.containerFactory" property).
Second, for the JSPs too, similar to the above, I think EmbeddedGlassFish test container type should be helpful. Might be the GrizzlyWeb test container type could be modified to do something like that as well (I will have to investigate on that).
Posted by Naresh on October 01, 2009 at 08:36 AM PDT #
Naresh,
Thanks for the reply. I worked around the grizzly problem by using the lightweight http container. At this point I just want working unit tests, I don't really care about testing in multiple containers.
As far as the no such method error, I suspect NB 6.5 is providing jersey 1.0 where 1.0 < 1.0.3, so that must be my issue. Due to the way netbeans hooks into jersey (e.g. creating a restful web service automatically ads jersey to the project dependencies if it isn't already there), I'm not sure how to upgrade jersey versions without upgrading NB, and I'm not ready to do that yet.
Thanks
Posted by Brian on October 01, 2009 at 12:32 PM PDT #
I'm trying to figure out how to pass queryParams from the test framework.
This doesn't work:
String responseMsg = webResource.path("message/55?name=Tom").get(String.class);
I think I want to do:
webResource.getBuilder().queryParam("name", "Tom").path("messages/55"), but this returns a UriBuilder or a URI and I'm not sure how to get from either to a webResource.
Posted by Brian on October 06, 2009 at 08:10 AM PDT #
Ok, I just answered my own question.
URI uri = webResource.getBuilder().queryParam("name", "Tom").path("messages/{a}").build("55");
String responseMsg = webResource.uri(uri).get(String.class);
Posted by 24.124.29.17 on October 06, 2009 at 08:34 AM PDT #
Great to hear that you got it working :)
Posted by Naresh on October 06, 2009 at 09:01 AM PDT #
Note that to set the testcontainer in code, extend JerseyTest.configure():
protected AppDescriptor configure() {
this.setTestContainerFactory(new com.sun.jersey.test.framework.spi.container.inmemory.InMemoryTestContainerFactory());
return new WebAppDescriptor.Builder("com.example.web")
.contextPath("/").build(); }
Posted by Tarjei Huse on November 09, 2009 at 04:11 AM PST #
Hi Tarjei,
you could definitely use the code fragment that you had mentioned for configuring the default test container factory.
Alternatively, the following code fragment could be used too:
@Override
protected TestContainerFactory getTestContainerFactory() {
return new GrizzlyWebTestContainerFactory();
}
Posted by Naresh on November 09, 2009 at 06:23 AM PST #