Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 通过WebApplicationContext模拟HttpServlet中的属性_Java_Spring_Unit Testing_Jakarta Ee_Servlets - Fatal编程技术网

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中的字段this
myAttribute
可以在servlet的生命周期中随时初始化,那么就存在设计问题。您应该使用另一种机制,比如servlet init参数。
myAttribute
是一个只初始化一次的bean。此外,字段
myAttribute
本身在Servlet的重写
init()
-方法中仅初始化一次。这几乎不是生命周期中的任何时候。