I want to test a class like Example
that handles a ContextRefreshedEvent
and connects to a server in the handler method:
public class Example {
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
startWebSocketConnection();
}
// ...
}
But in the integration test the application context is built before the web socket server is up and running, so I get an exception saying that the connection failed (java.net.ConnectException: Connection refused: no further information
in this case).
The test looks like this:
@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest
public class WebSocketDataSourceTest {
@Autowired
private Example example;
@Autowired
private WebSocketServer server; // created too late
// ...
}
Is it somehow possible to suppress the ContextRefreshedEvent
or to defer the creation of the application context, so that the web socket server can start before? Or is there another solution?