gpt4 book ai didi

java - Spring 集成测试中 ContextRefreshedEvent 过早触发

转载 作者:行者123 更新时间:2023-12-02 10:50:55 24 4
gpt4 key购买 nike

我想测试像 Example 这样的类,它处理 ContextRefreshedEvent 并在处理程序方法中连接到服务器:

public class Example {

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
startWebSocketConnection();
}

// ...
}

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

测试如下所示:

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
public class WebSocketDataSourceTest {

@Autowired
private Example example;

@Autowired
private WebSocketServer server; // created too late

// ...
}

是否可以以某种方式抑制ContextRefreshedEvent或推迟应用程序上下文的创建,以便Web套接字服务器可以提前启动?或者还有其他解决方案吗?

最佳答案

似乎没有办法抑制 Spring 框架触发的事件或推迟应用程序上下文的创建。所以我想出了以下解决方法:

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
// ...
}
}

关于java - Spring 集成测试中 ContextRefreshedEvent 过早触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52198636/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com