dj aqeel dj aqeel - 1 year ago 127
Java Question

How to get instance of

Is there any implementation of
which I can use to create an instance quickly for testing. This interface is long, I just need to test something. I don't want to waste time on whole implementation of this interface.

UPDATE: I want to write a unit test for a function similar to this:

public String webserviceRequest(@Context UriInfo uriInfo);

Answer Source

You simply inject it with the @Context annotation, as a field or method parameter.

public class Resource {
    UriInfo uriInfo;

    public Response doSomthing(@Context UriInfo uriInfo) {


Other than your resource classes, it can also be injected into other providers, like ContainerRequestContext, ContextResolver, MessageBodyReader etc.


Actually I want to write a junit test for a function similar to your doSomthing() function.

I didn't pick that up in your post. But a couple options I can think of for unit tests

  1. Simply create a stub, implementing only the methods you use.

  2. Use a Mocking framework like Mockito, and mock the UriInfo. Example

    public class TestResource { 
        public String doSomthing(@Context UriInfo uriInfo){
            return uriInfo.getAbsolutePath().toString();
    public void doTest() {
        UriInfo uriInfo = Mockito.mock(UriInfo.class);
        TestResource resource = new TestResource();
        String response = resource.doSomthing(uriInfo);
        Assert.assertEquals("http://localhost:8080/test", response);

    You'll need to add this dependency


If you want to do an integration test, where the actual UriInfo is injected, you should look into Jersey Test Framework

Here's a complete example with the Jersey Test Framework

public class ResourceTest extends JerseyTest {

    public static class TestResource {
        public Response doSomthing(@Context UriInfo uriInfo) {
            return Response.ok(uriInfo.getAbsolutePath().toString()).build();

    public Application configure() {
        return new ResourceConfig(TestResource.class);

    public void test() {
        String response = target("test").request().get(String.class);

Just add this dependency


It uses an in-memory container, which is the most efficient for small tests. There are other containers with Servlet support if needed. Just see the link I posted above.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download