[英]How to inject servletcontext for junit test cases which are autowired in source controller
我有一个控制器类,其中ServletContext是自动连接的。
@Controller
public class BaseController {
@Autowired
private ServletContext servletContext;
protected ServletContext getServletContext() {
return servletContext;
}
public Object getBean(String beanName) {
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.servletContext);
return appContext.getBean(beanName);
}
}
BaseController
的getBean()
由扩展它的子类中的许多方法使用。
当我尝试为子类中的方法(调用getBean()
)执行jUnit测试用例时,出现以下错误。
java.lang.IllegalArgumentException: ServletContext must not be null
我无法在运行junit时加载web.xml。
有人可以帮忙解释一下如何从JUnit设置servlet上下文吗? 如果解决方案是MockServletContext
,请提供一个代码片段,说明如何将MockServletContext
注入到控制器中自动连接的ServletContext上。
注意: BaseController
没有BaseController
setServletContext()
您可以使用PowerMock的WhiteBox设置servletContext。
WhiteBox.setInternalState(controller, "servletContext", yourServletContext);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.