Java 通过WebApplicationContext模拟HttpServlet中的属性
假设我有一个带有属性(Java 通过WebApplicationContext模拟HttpServlet中的属性,java,spring,unit-testing,jakarta-ee,servlets,Java,Spring,Unit Testing,Jakarta Ee,Servlets,假设我有一个带有属性(MyAttribute)的HttpServlet。在servlet初始化之后,我想用一个mock替换后者 我正在重写的MyServlet.init()方法中实例化我的属性,如下所示: WebApplicationContext wac = getWebApplicationContext(); this.myAttribute = (MyAttribute) wac.getBean("myAttribute"); MyServlet myServlet = (MyServ
MyAttribute
)的HttpServlet
。在servlet初始化之后,我想用一个mock替换后者
我正在重写的MyServlet.init()方法中实例化我的属性,如下所示:
WebApplicationContext wac = getWebApplicationContext();
this.myAttribute = (MyAttribute) wac.getBean("myAttribute");
MyServlet myServlet = (MyServlet) WebApplicationContext.getServletContext().getServlet("myServlet");
myServlet.setMyAttribute(EasyMock.createStrictMock(MyAttribute.class));
现在,在我的单元测试中,我得到的只是一个WebApplicationContext
对象。1
我计划这样模拟属性:
WebApplicationContext wac = getWebApplicationContext();
this.myAttribute = (MyAttribute) wac.getBean("myAttribute");
MyServlet myServlet = (MyServlet) WebApplicationContext.getServletContext().getServlet("myServlet");
myServlet.setMyAttribute(EasyMock.createStrictMock(MyAttribute.class));
不幸的是,ServletContext().getServlet()
方法已被弃用,当前返回的总是null
,并将在将来的版本中永久删除。因此,我的问题是:
如何通过WebApplicationContext模拟HttpServlet的属性?
1:这是因为我的单元测试在自己的线程中启动了一个Tomcat'ish服务器实例,并在它启动并运行后返回我的应用程序的WebApplicationContext。是否要在Servlet中填充属性?如果这个servlet属性是servlet中的一个普通字段,并且可以在servlet的生命周期中多次实例化,那么它看起来就像servlet类中的一个设计问题。我建议在会话中设置属性,或者根据需要将数据作为请求参数传递。不,实际上Servlet委托给另一个类MyAttribute
。我想用一个模拟的类来交换这个类的实例。同样,如果servlet中的字段thismyAttribute
可以在servlet的生命周期中随时初始化,那么就存在设计问题。您应该使用另一种机制,比如servlet init参数。myAttribute
是一个只初始化一次的bean。此外,字段myAttribute
本身在Servlet的重写init()
-方法中仅初始化一次。这几乎不是生命周期中的任何时候。