views:

391

answers:

2

I'm unit testing with jetty and I want to serve not only my servlet under test but a static page as well. The static page is needed by my application. I'm initializing jetty like this

tester = new ServletTester();
tester.setContextPath("/context");
tester.addServlet(MyServlet.class, "/servlet/*");
tester.start();

What I need now, is something like

tester.addStaticPage("local/path/in/my/workspace", "/as/remote/file");

Is this possible with jetty?

A: 

Propably this site will help you:

Serving Static content with Jetty

furtelwart
+1  A: 

I don't think you can do this with ServletTester. ServletTester creates a single Context for the servlet. You need to set up embedded jetty with at least two contexts: one for the servlet, and one for the static content.

If there was a full WebAppContext, you'd be set, but there isn't.

You could make a copy of ServletTester and add hair, or you can just read up on the API and configure the necessary contexts. Here's a code fragment to show you the basic idea, you will not be able to compile this as-is. You will need to create a suitable context for the static content.

        server = new Server();

        int port = Integer.parseInt(portNumber);
        if (connector == null) {
            connector = createConnector(port);
        }
        server.addConnector(connector);

        for (Webapp webapp : webapps) {
            File sourceDirFile = new File(webapp.getWebappSourceDirectory());
            WebAppContext wac = new WebAppContext(sourceDirFile.getCanonicalPath(), webapp.getContextPath());
            WebAppClassLoader loader = new WebAppClassLoader(wac);
            if (webapp.getLibDirectory() != null) {
                Resource r = Resource.newResource(webapp.getLibDirectory());
                loader.addJars(r);
            }
            if (webapp.getClasspathEntries() != null) {
                for (String dir : webapp.getClasspathEntries()) {
                    loader.addClassPath(dir);
                }
            }
            wac.setClassLoader(loader);
            server.addHandler(wac);
        }
        server.start();
bmargulies
Thanks for your response. I thought that ServletTester won't give me as much choice. I don't know if I want to setup a full jetty server for my unit test, but I'll take a look at it.
cringe