0

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?

deamon
  • 89,107
  • 111
  • 320
  • 448

1 Answers1

2

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
        // ...
    }
}
deamon
  • 89,107
  • 111
  • 320
  • 448