Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test JERSEY controller methods with UriInfo

I am writing unit test for a JERSEY project.

For methods with no query string , I can just instantiate controller and call the method.

Also work for argument in the path because they appear as string arguments of the method.

But when I get queryStrings the mode has a special argument (@Context UriInfo url)

How can I build the UriInfo argument in my unit tests ? Why does this class has no constructor ?

like image 431
Frederic Bazin Avatar asked Mar 09 '13 12:03

Frederic Bazin


2 Answers

If you're using Mockito in your tests, you could mock out UriInfo instead:

import java.net.URI;
import javax.ws.rs.core.UriInfo;

UriInfo mockUriInfo = mock(UriInfo.class);
when(mockUriInfo.getRequestUri()).thenReturn(new URI("http://www.test.com/go"));
like image 171
Brad Parks Avatar answered Nov 01 '22 02:11

Brad Parks


UriInfo is an interface so you can't create its object directly. You need to subclass it and create your own UriInfo class. So your uriinfo class should convert String uri/url into UriInfo object.

public class UriInformation implements UriInfo {
    MultivaluedMap<String, String> pathParamMap;
    MultivaluedMap<String, String> queryParamMap;
    public UriInformation(UriInfo uriInfo) {
        //parse uriInfo 
    }
 //setters/getters
}

So this way you can unit test your resources without running it inside tomcat/server.

like image 22
rai.skumar Avatar answered Nov 01 '22 04:11

rai.skumar