Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Jetty Server with JUnit tests

I've been trying to test my web app by starting a Jetty server in the BeforeClass method of my JUnit test case and then using a HttpClient to form request to the server. I get the server to start without any issues, but I keep getting 404's when I try to make a request.

The configuration of my server is like the following:

  public void start() throws Exception {
        if (server == null) {
            server = new Server(PORT);
            server.setStopAtShutdown(true);

            wac = new WebAppContext();
            wac.setContextPath("/app");
            wac.setResourceBase("war");
            wac.setClassLoader(this.getClass().getClassLoader());
            server.addHandler(wac);

            server.start();
        }
   }    

Is there something wrong with my config? The server is running, and I can see that I am hitting it, it just can't find any resources.

like image 329
stevebot Avatar asked Nov 29 '22 18:11

stevebot


1 Answers

This is a complete Junit test class that uses jetty:

package test.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;

public class MockPortalTest {

    private Server server;

    @Before
    public void startServer() throws Exception {
        server = new Server(8080);
        server.setStopAtShutdown(true);
        WebAppContext webAppContext = new WebAppContext();
        webAppContext.setContextPath("/app");
        webAppContext.setResourceBase("src/main/webapp");       
        webAppContext.setClassLoader(getClass().getClassLoader());
        server.addHandler(webAppContext);
        server.start();
    }


    @Test
    public void shouldBePreAuthenticated() throws Exception {
        String userId = "invalid";
        HttpClient client = new DefaultHttpClient();
        HttpGet mockRequest = new HttpGet("http://localhost:8080/app");
        mockRequest.setHeader("http-user",userId);
        HttpResponse mockResponse = client.execute(mockRequest);
        BufferedReader rd = new BufferedReader
          (new InputStreamReader(mockResponse.getEntity().getContent()));    
        // DO YOUR ASSERTIONS
    }

    @After
    public void shutdownServer() throws Exception {
        server.stop();
    }

}
like image 68
Christian Achilli Avatar answered Dec 06 '22 11:12

Christian Achilli