Access Spring beans in JerseyTest

I am trying to figure out how to access Spring beans from a subclass of JerseyTest. JerseyTest Extension I was able to load the Spring context in my tests, but I did not understand how to access the Spring context. My setup looks like this:

public abstract class SpringJerseyTest extends JerseyTest { public SpringJerseyTest() throws Exception { super(new WebAppDescriptor.Builder("com.acme.resources") .contextPath("/") .contextParam("contextConfigLocation", "classpath:applicationContext.xml") .servletClass(SpringServlet.class) .contextListenerClass(ContextLoaderListener.class) .build()); } } 

The settings use the default Grizzly Web Container. I had never used Grizzly before, but in Jetty I would do something like this:

  public Object getSpringBean(String beanName) { WebAppContext context = (WebAppContext) server.getHandler(); ServletContext sc = context.getServletContext(); WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc); return applicationContext.getBean(beanName); } 

Can someone point me in the right direction?

+7
source share
3 answers

Using the solution described here for a week, and it works fine.

+2
source

I use a naive approach, but it works

 public ResourceIT() { super(new WebAppDescriptor.Builder("amazingpackage") .servletClass(SpringServlet.class) .contextParam("contextConfigLocation", "classpath:/spring/context.xml") .contextListenerClass(ContextLoaderListener.class) .contextPath("context") .build()); injectedBean = ContextLoaderListener .getCurrentWebApplicationContext().getBean(InjectedBean.class); } 
+10
source

I do not understand the needs of the JerseyTest that uses the Spring bean, often your Spring Beans is the Service / Dao level, and they should be Unit test / Integration Test on their layer using Mockito or DBUnit (integration tests).

I participated in testing Jersey resource classes using Sprig Beans as a mockery because you only need to isolate the tests and test the Jersey (and Json) stuff on the JerseyTest and not on the service or Dao Layer. follow my Spring bean context, but Spring Beans are only mocks because I don't want to test Spring Beans in JerseyTests.

If you isolate your tests, it would be easier to write and maintain tests

-one
source

All Articles