[英]Accessing Spring beans in JerseyTest
我試圖弄清楚如何從JerseyTest的子類訪問Spring bean。 擴展JerseyTest我已經設法在我的測試中加載Spring上下文,但我還沒弄清楚如何訪問spring上下文。 我的設置如下:
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());
}
}
該設置使用默認的Grizzly Web容器。 我之前從未使用Grizzly,但在Jetty中我會做這樣的事情:
public Object getSpringBean(String beanName) {
WebAppContext context = (WebAppContext) server.getHandler();
ServletContext sc = context.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
return applicationContext.getBean(beanName);
}
有人能指出我正確的方向嗎?
我正在使用一種天真的方法,但有效
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);
}
使用這里描述的解決方案一周,它工作正常。
我不明白使用Spring bean的JerseyTest的需要,通常你的Spring Beans是Service / Dao層,他們必須在他們的層上進行單元測試/集成測試,使用Mockito或DBUnit(集成測試)。
我一直在使用Sprig bean作為模擬單元測試Jersey資源類,這是因為你必須隔離測試,並且只測試JerseyTest中的Jersey東西(和Json),而不是Service或Dao Layer。是的,我確實通過了我的spring bean上下文,但春豆只是嘲笑,因為我不想測試JerseyTests中的春豆。
如果您隔離測試,則編寫和維護測試會更容易
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.