I am developing an API for a real-time multiplayer game and aim to create integration tests for my STOMP API. While using mocks in integration tests is unconventional, I want to verify that the correct endpoints and methods are accessed during specific events.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = {"spring.main.allow-bean-definition-overriding=true"})
public class PublishToServerTest {
@LocalServerPort
private int port;
@MockBean
private SimpMessagingTemplate messagingTemplate;
@MockBean
private LobbyService lobbyService;
@Test
public void testPublishPlayerToLobby() throws InterruptedException {
var timeout = 3; // Seconds
var webSocketClient = new StandardWebSocketClient();
var stompClient = new WebSocketStompClient(webSocketClient);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
stompClient.setTaskScheduler(new DefaultManagedTaskScheduler());
var sessionHandler = new ExtendedStompSessionHandler() {
@Override
public void afterConnected(StompSession session, @NonNull StompHeaders connectedHeaders) {
var clientPayload = new IncomingPlayerClientPayload("0", 0);
session.send("/game/seek-opponent", clientPayload);
verify(lobbyService).matchPlayer(any());
getLatch().countDown();
}
@Override
public void handleException(@NonNull StompSession session, StompCommand command, @NonNull StompHeaders headers, @NonNull byte[] payload, @NonNull Throwable exception) {
fail(exception.getMessage());
}
};
stompClient.connectAsync(String.format("ws://localhost:%d/ws", port), sessionHandler);
var messageSent = sessionHandler.getLatch().await(timeout, TimeUnit.SECONDS);
assertTrue(messageSent);
}
LobbyService
is responsible for creating new records in my Firestore database. As expected, when I mock this service, no database interactions occur during the test, and I will be able to confirm that the correct method is accessed. However, the verify(lobbyService).matchPlayer(any()) call fails, saying that the method interaction is not being detected by Mockito.
Wanted but not invoked:
lobbyService bean.matchPlayer(<any>);
Kenuff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.