Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.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 测试SpringWebListener_Java_Spring - Fatal编程技术网

Java 测试SpringWebListener

Java 测试SpringWebListener,java,spring,Java,Spring,我有一个用@WebListener注释的类,它扩展了我正在测试的另一个类所依赖的ServletContextListener。当我手动测试(即在Tomcat中运行)时,它可以工作,但在我的JUnit测试中,@WebListener类永远不会执行。我假设我需要在配置中添加一些东西来让它执行,但我不确定是什么。或者我需要在测试中手动运行它吗 编辑: 以下是本课程的基本知识 @WebListener public class MyListener implements ServletContextLi

我有一个用@WebListener注释的类,它扩展了我正在测试的另一个类所依赖的ServletContextListener。当我手动测试(即在Tomcat中运行)时,它可以工作,但在我的JUnit测试中,@WebListener类永远不会执行。我假设我需要在配置中添加一些东西来让它执行,但我不确定是什么。或者我需要在测试中手动运行它吗

编辑: 以下是本课程的基本知识

@WebListener
public class MyListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent event) {
    // Retrieve spring application context
    ServletContext servletContext = event.getServletContext();
    springContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
    ...
  }
  ...
}
我已将以下内容添加到我的测试类:

@Before
public void mockInit() {
    MockServletContext mockContext = new MockServletContext();
    new MyListener().contextInitialized(new ServletContextEvent(mockContext));
}

但是
contextInitialized
中的
springContext
变量为空

我错过了几件事。首先,我的测试类没有@WebAppConfiguration

@WebAppConfiguration
public class ClassAbcTest extends TestBase {
  ...
}
其次,我需要设置根应用程序上下文:

@Autowired
private WebApplicationContext webAppContext;

@Before
public void mockInit() {
  MockServletContext mockServletContext = new MockServletContext();
  mockServletContext.setAttribute(
    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webAppContext);
  new MyListener().contextInitialized(new ServletContextEvent(
    mockServletContext));
}

我意识到这是一个老问题,但我意外地找到了一个答案,这里没有显示

我在Spring Boot应用程序中使用了一个嵌入式Apache FTP服务器,该服务器由
@WebListener

Web侦听器类丢失,在Junit测试期间无法进行FTP连接

下面的注释修复了它

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
我希望这个答案能像帮助我一样帮助那些偶然发现这一页的人