ContextRefreshedEvent fired too early in Spring integration test
ContextRefreshedEvent fired too early in Spring integration test
I want to test a class like Example that handles a ContextRefreshedEvent and connects to a server in the handler method:
Example
ContextRefreshedEvent
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).
java.net.ConnectException: Connection refused: no further information
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?
ContextRefreshedEvent
1 Answer
1
There seems to be no way to suppress an event fired by the Spring framework or to defer the application context creation. So I came up with the following workaround:
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();
// ...
The test triggers the event handler manually.
@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
// ...
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.