Websocket Tests
Websocket Tests
Websocket Tests
controllers;
import dev.backend.tutor.dtos.MessageDto;
import dev.backend.tutor.entities.Student;
import dev.backend.tutor.repositories.StudentRepository;
import dev.backend.tutor.utils.StudentGenerator;
import dev.backend.tutor.utils.WsTestUtils;
import dev.backend.tutor.sevices.messages.MessageService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import
org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.messaging.simp.stomp.StompSession;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.socket.messaging.WebSocketStompClient;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.lifecycle.Startables;
import java.util.concurrent.CompletableFuture;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT)
public class FriendControllerTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgreSQLContainer = new
PostgreSQLContainer<>("postgres:alpine");
@DynamicPropertySource
public static void setUpThings(DynamicPropertyRegistry registry) {
Startables.deepStart(postgreSQLContainer).join();
}
@Autowired
private StudentRepository studentRepository;
@Autowired
private MessageService messageService;
@Before
public void setUp() throws Exception {
String wsUrl = "ws://localhost:8080" + "/add_friend";
stompClient = wsTestUtils.createWebSocketClient();
stompSession = stompClient.connectAsync(wsUrl, new
WsTestUtils.MyStompSessionHandler()).get();
}
@After
public void tearDown() {
stompSession.disconnect();
stompClient.stop();
}
@Test
public void connectsToSocket() {
assertThat(stompSession.isConnected()).isTrue();
}
record StudentAndResultKeeper(Student student, CompletableFuture<String>
resultKeeper){}
@Test
public void receivesMessageFromSubscribedQueue() throws Exception {
//given
var senderStudentData = initStudent("senderLogin");
var recipientStudentData = initStudent("recipientLogin");
//when
messageService.sendMessageToUser(recipientStudent.getUsername(),
messageDto);
//then
var result = resultKeeper.get(2, SECONDS);
System.out.println(result);
assertThat(result).isEqualTo(messageDto.toString());
}