kknd22
6/6/2014 - 12:08 PM

xml-less spring jersey test

xml-less spring jersey test

package t;

import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spring.SpringLifecycleListener;
import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.inmemory.InMemoryTestContainerFactory;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;

import static org.junit.Assert.assertEquals;

public class SampleEndpointTest extends JerseyTest {
    //private ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);

    public SampleEndpointTest()
    {
        super(new InMemoryTestContainerFactory());
    }




    public static class MySpringInjectable {
        public int i = 0;
    }

    public static class AppConfig {

        @Bean
        public MySpringInjectable myInjectablePerRequest() {
            return new MySpringInjectable();
        }
    }

    @Path("/")
    public static class Resource {

        public MySpringInjectable mySpringInjectable;

        @Autowired
        public Resource(MySpringInjectable mySpringInjectable)
        {
            this.mySpringInjectable = mySpringInjectable;
        }

        @GET
        @Path("/singleton")
        public String getAndIncPerRequest() {
            return Integer.valueOf(++mySpringInjectable.i).toString();
        }
    }


    @Override
    protected Application configure() {
        ResourceConfig rc = new ResourceConfig();
        rc.property("contextConfig", new AnnotationConfigApplicationContext(AppConfig.class));
        rc.register(SpringLifecycleListener.class).register(RequestContextFilter.class);
        rc.registerClasses(Resource.class);

        return rc;
    }

    @Test
    public void test1()
    {
        final javax.ws.rs.client.WebTarget singleton = target().path("singleton");

        assertEquals("1", singleton.request().get(String.class));
        assertEquals("2", singleton.request().get(String.class));
        assertEquals("3", singleton.request().get(String.class));


    }
}