Skip to content

Instantly share code, notes, and snippets.

@kknd22
Created June 6, 2014 12:08
Show Gist options
  • Save kknd22/301774dc3b407dd57b81 to your computer and use it in GitHub Desktop.
Save kknd22/301774dc3b407dd57b81 to your computer and use it in GitHub Desktop.
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));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment