代码之家  ›  专栏  ›  技术社区  ›  deamon

ContextRefreshedEvent在Spring集成测试中触发得太早

  •  0
  • deamon  · 技术社区  · 8 年前

    Example 处理一个 ContextRefreshedEvent

    public class Example {
    
        @EventListener
        public void onApplicationEvent(ContextRefreshedEvent event) {
            startWebSocketConnection();
        }
    
        // ...
    }
    

    但是在集成测试中,应用程序上下文是在websocket服务器启动并运行之前构建的,所以我得到一个异常,表示连接失败( java.net.ConnectException: Connection refused: no further information 在这种情况下)。

    测试如下所示:

    @ExtendWith(SpringExtension.class)
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    @SpringBootTest
    public class WebSocketDataSourceTest {
    
        @Autowired 
        private Example example;
    
        @Autowired
        private WebSocketServer server; // created too late
    
        // ...
    }
    

    有没有可能抑制 或者推迟应用程序上下文的创建,以便websocket服务器可以在之前启动?还是有别的解决办法?

    1 回复  |  直到 8 年前
        1
  •  1
  •   deamon    8 年前

    import org.springframework.core.env.Environment;
    
    public class Example {
    
        private boolean skipNextEvent;
    
        @Autowired
        public Example(Environment environment) {
            skipNextEvent = environment.acceptsProfiles("test");
        }
    
        @EventListener
        public void onApplicationEvent(ContextRefreshedEvent event) {
            if (skipNextEvent) {
                skipNextEvent = false;
                return;
            }
            startWebSocketConnection();
        }
    
        // ...
    }
    

    测试手动触发事件处理程序。

    @ExtendWith(SpringExtension.class)
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    @SpringBootTest
    @ActiveProfiles("test") // set profile "test"
    public class WebSocketDataSourceTest {
    
        @Autowired 
        private Example example;
    
        @Autowired
        private WebSocketServer server;
    
        @Test
        public void shouldWork() {
            // ...
            example.onApplicationEvent(null); // trigger manually
            // ...
        }
    }