2

I am trying to get a simple unit test to work, however it returns a 404 status.

Enpoints Class:

@Path("/v1")
public class Endpoints {

    @Context
    private HttpServletResponse servletResponse;

    private void allowCrossDomainAccess() {
        if (servletResponse != null){
            servletResponse.setHeader("Access-Control-Allow-Origin", "*");
        }
    }

    @GET
    @Path("/whoami")
    @Produces(MediaType.APPLICATION_JSON)
    public String whoami(@Context final HttpServletRequest request){
        allowCrossDomainAccess();

        // Extract the software version from the user agent 
        final String userAgent = request.getHeader("user-agent");
        final Pattern pattern = Pattern.compile("\\((.+?)\\)"); // Regex to extract anything between opening and closing curly bracers
        final Matcher matcher = pattern.matcher(userAgent);
        matcher.find();
        final String software = matcher.group(1);

        final String ipAddress; 
        if (request.getHeader("X-Forwarded-For") != null){ // Heroku adds this header
            ipAddress = request.getHeader("X-Forwarded-For");
        } else {
            ipAddress = request.getRemoteAddr();
        }

        final JSONObject json = new JSONObject();
        json.put("ipaddress", ipAddress);
        json.put("locale", request.getLocale());
        json.put("software", software);

        return json.toString(4);
    }

}

My Test Class:

public class EndpointsTest extends JerseyTest {

    @Override
    protected Application configure() {
        return new ResourceConfig(Endpoints.class);
    }

    @Test
    public void parseHeadersTest() {
        Response output = target().path("/api/v1/whoami").request().get();
        System.out.println("response: " + output);
        assertEquals(200, output.getStatus());
    }
}

Output:

Jul 15, 2016 2:30:37 PM org.glassfish.jersey.test.grizzly.GrizzlyTestContainerFactory$GrizzlyTestContainer <init>
INFO: Creating GrizzlyTestContainer configured at the base URI http://localhost:9998/
Jul 15, 2016 2:30:37 PM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [localhost:9998]
Jul 15, 2016 2:30:37 PM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
response: InboundJaxrsResponse{context=ClientResponse{method=GET, uri=http://localhost:9998/api/v1/whoami, status=404, reason=Not Found}}
Jul 15, 2016 2:30:37 PM org.glassfish.grizzly.http.server.NetworkListener shutdownNow
INFO: Stopped listener bound to [localhost:9998]

As you can see, the resposne returns a 404 error. If I start the server by running the Main class outside of a unit test and navigate to the URI of the response (http://localhost:9998/api/v1/whoami) it works perfectly.

Why doesn't my unit test work?

EDIT

public class Main {

    public static void main(String[] args) throws Exception{
        // The port that we should run on can be set into an environment variable
        // Look for that variable and default to 8080 if it isn't there.
        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = "9998";
        }

        final Server server = new Server(Integer.valueOf(webPort));
        final WebAppContext root = new WebAppContext();

        root.setContextPath("/");
        // Parent loader priority is a class loader setting that Jetty accepts.
        // By default Jetty will behave like most web containers in that it will
        // allow your application to replace non-server libraries that are part of the
        // container. Setting parent loader priority to true changes this behavior.
        // Read more here: http://wiki.eclipse.org/Jetty/Reference/Jetty_Classloading
        root.setParentLoaderPriority(true);

        final String webappDirLocation = "src/main/webapp/";
        root.setDescriptor(webappDirLocation + "/WEB-INF/web.xml");
        root.setResourceBase(webappDirLocation);

        server.setHandler(root);

        server.start();
        server.join();
    }

}

WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        version="3.0">

    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.rich.fcc</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>
</web-app>
rj93
  • 523
  • 8
  • 25
  • We might need to see your configuration. It seems as if the server did not register the endpoint when started during the unit test. – Dave Jul 15 '16 at 13:41
  • @sdotdi I've editted the question to include everything which I think is relevant – rj93 Jul 15 '16 at 13:49
  • 2
    Drop the `/api` in the `path(..)` – Paul Samsotha Jul 15 '16 at 15:02
  • @peeskillet when I make it `Response output = target().path("/v1/whoami").request().get()` the response is: `response: InboundJaxrsResponse{context=ClientResponse{method=GET, uri=http://localhost:9998/v1/whoami, status=500, reason=Request failed.}}`. – rj93 Jul 15 '16 at 15:05
  • 1
    You have an error in the server side you need to fix. At least now you are actually hitting the server – Paul Samsotha Jul 15 '16 at 15:11
  • You need to configure a servlet environment. See [here](http://stackoverflow.com/q/28436040/2587435). Most likely you getting an NPE on the HttpSevletRequest because you aren't running a servlet environment – Paul Samsotha Jul 15 '16 at 15:15
  • @peeskillet Thank you! It was a NullPointerException. Annoying how the exception never gets outputted. Spent hours trying to get this to work! – rj93 Jul 15 '16 at 15:26

0 Answers0