[英]How to inject servletcontext for junit test cases which are autowired in source controller
I have a controller class in which, servletContext is autowired. 我有一个控制器类,其中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);
}
}
The getBean()
in BaseController
is used by many methods in subclasses extending it. BaseController
的getBean()
由扩展它的子类中的许多方法使用。
When I tried to execute jUnit test cases for the methods in subclasses (which were invoking getBean()
), I was getting the below error. 当我尝试为子类中的方法(调用getBean()
)执行jUnit测试用例时,出现以下错误。
java.lang.IllegalArgumentException: ServletContext must not be null
I am unable to load web.xml while running junit. 我无法在运行junit时加载web.xml。
Can someone please help in explaining , on how to set servlet context from JUnit ? 有人可以帮忙解释一下如何从JUnit设置servlet上下文吗? If MockServletContext
is the solution, please provide a code snippet on how to inject MockServletContext
, to the autowired servletContext in the controller. 如果解决方案是MockServletContext
,请提供一个代码片段,说明如何将MockServletContext
注入到控制器中自动连接的ServletContext上。
Note : There is no setServletContext()
in BaseController
注意: BaseController
没有BaseController
setServletContext()
您可以使用PowerMock的WhiteBox设置servletContext。
WhiteBox.setInternalState(controller, "servletContext", yourServletContext);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.