Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet context injection fail while using jersey test framework

I'm beginning with jersey and trying to get freemarker working with it using TDD. I want to make a ViewProcessor for my templates, but fail to inject the servlet context in the class.

Here is the class code :

@Provider
public class myProcessor implements ViewProcessor<Template> {

    [...]
   
    @Context
    public ServletContext myContext;

    [...]

 freemarkerConfiguration.setTemplateLoader(
       new WebappTemplateLoader(myContext,
           myContext.getInitParameter("freemarker.template.path")));

    [...]
    }

And here is the test code :

public class myProcessorTest extends JerseyTest {
   
    public static myProcessor mp;
   
    public myProcessorTest() throws Exception{
        super(new WebAppDescriptor.Builder("com.domain").build());
    }
   
    @Test
    public void firstTest(){
        mp = new myProcessor();
        String path = new String("test.ftl");
        Template template = mp.resolve(path);
        assertNotNull(template);
    }
}

I use maven with dependencies as follow:

<dependency>
    <groupId>com.sun.jersey.jersey-test-framework</groupId>
    <artifactId>jersey-test-framework-grizzly</artifactId>
    <version>1.5-SNAPSHOT</version>
    <scope>test</scope>
</dependency>

My code runs fine when I deploy to my local jetty server. But if I want to test the code in my IDE, it failed to inject the servlet context (@Context) : myContext is null when I run the test :/

I think I'm missing something, but I'm a complete beginner with servlet world.

like image 653
Balistick Avatar asked Dec 02 '10 12:12

Balistick


1 Answers

Here's a technique for testing a specific resource class, using Jersey Test Framework, with servlet support. Also demonstrates how to customize the ServletContext.

import javax.servlet.ServletContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.ServletDeploymentContext;
import org.glassfish.jersey.test.TestProperties;
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;

import static org.mockito.Mockito.mock;

/**
 * A base class for testing web resources.
 */
public abstract class WebResourceTest extends JerseyTest {

    /**
     * Creates a JAX-RS resource configuration for test purposes.
     */
    @Override
    protected abstract ResourceConfig configure();

    /**
     * Creates a test container factory with servlet support.
     */
    @Override
    protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
        return new GrizzlyWebTestContainerFactory();
    }

    /**
     * Configures a deployment context for JAX-RS.
     */
    @Override
    protected DeploymentContext configureDeployment() {
        ResourceConfig app = configure();
        app.register(new Feature() {
            @Context
            ServletContext servletContext;

            @Override
            public boolean configure(FeatureContext context) {
                servletContext.setAttribute("example", new Object());
                return true;
            }
        });
        return ServletDeploymentContext.forServlet(new ServletContainer(app)).build();
    }
}

A usage example:

import org.glassfish.jersey.server.ResourceConfig;
import javax.ws.rs.core.Context;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.core.Response;
import static org.mockito.Mockito.spy;
import static org.testng.Assert.assertEquals;
import static org.junit.Assert.*;

public class MyResourceTest extends WebResourceTest {

    private MyResource resource;

    @Override
    protected ResourceConfig configure() {
        resource = spy(new MyResource());
        return new ResourceConfig().register(resource);
    }

    @Test
    public void testSomething() {
        Response r = target("/myresource").request().get();
        assertEquals(200, r.getStatus());
        assertEquals(1, resource.count);
    }
}

@Path("/myresource")
public class MyResource {
    int count = 0;

    @Context
    protected ServletContext servletContext;

    @GET
    public void get() {
       Object attr = servletContext.getAttribute("example");
       count++;
    }
}
like image 74
Eron Wright Avatar answered Nov 11 '22 00:11

Eron Wright