Skip to content

Commit

Permalink
refactor: removed and faxed tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Troha7 committed Jan 17, 2024
1 parent 0e291f7 commit 18b7263
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 92 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import com.chat.yourway.dto.request.MessagePrivateRequestDto;
import com.chat.yourway.dto.request.MessagePublicRequestDto;
import com.chat.yourway.dto.request.PageRequestDto;
import com.chat.yourway.dto.response.MessageNotificationResponseDto;
import com.chat.yourway.dto.response.MessageResponseDto;
import com.chat.yourway.integration.controller.websocketclient.TestStompFrameHandler;
Expand Down Expand Up @@ -165,13 +166,18 @@ void sendToContact_shouldReturnCorrectReceivedPrivateMessageFromSelfToSelf() {
void getMessages_shouldReturnReceivedMessagesHistoryFromTopic() {
// Given
int topicId = 12;
PageRequestDto pageRequestDto = new PageRequestDto(0, 10);
//Stored subscription results for testing
CompletableFuture<MessageResponseDto[]> resultKeeper = new CompletableFuture<>();

// Subscribe to topic
session.subscribe("/user/topic/" + topicId,
new TestStompFrameHandler<>(resultKeeper, objectMapper, MessageResponseDto[].class));

// Get topic message history
byte[] pageBytes = objectMapper.writeValueAsBytes(pageRequestDto);
session.send("/app/history/topic/" + topicId, pageBytes);

// Then
MessageResponseDto[] messageResponseDtos = resultKeeper.get(3, SECONDS);
assertThat(messageResponseDtos).isNotNull();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@
package com.chat.yourway.integration.controller;

import static com.github.springtestdbunit.annotation.DatabaseOperation.CLEAN_INSERT;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.chat.yourway.integration.extension.PostgresExtension;
import com.chat.yourway.integration.extension.RedisExtension;
import com.chat.yourway.model.Message;
import com.chat.yourway.repository.MessageRepository;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand All @@ -28,7 +20,6 @@
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;

@ExtendWith({PostgresExtension.class, RedisExtension.class})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
Expand All @@ -50,44 +41,8 @@ public class MessageControllerTest {
@Autowired
private MockMvc mockMvc;

@Autowired
private MessageRepository messageRepository;

private static final String URI = "/messages/";

//-----------------------------------
// GET
//-----------------------------------

@Test
@DisplayName("findAllByTopicId should return empty list of all messages by topic id")
void findAllByTopicId_shouldReturnEmptyListOfAllMessagesByTopicId() throws Exception {
// When
int notExistingTopicId = 99;
var result = mockMvc.perform(get(URI + "all/" + notExistingTopicId));

// Then
result
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON))
.andExpect(content().json("[]"));
}

@Test
@DisplayName("findAllByTopicId should return list of all messages by topic id")
public void findAllByTopicId_shouldReturnListOfAllMessagesByTopicId() throws Exception {
// Given
int topicId = 11;
List<Message> messages = messageRepository.findAllByTopicId(topicId);

// When
var result = mockMvc.perform(get(URI + "all/" + topicId));

// Then
result.andExpect(status().isOk());
assertMessagesEquals(result, messages);
}

//-----------------------------------
// POST
//-----------------------------------
Expand Down Expand Up @@ -137,25 +92,4 @@ public void reportMessage_shouldReturn400ForAlreadyReportedMessage() throws Exce
result.andExpect(status().isBadRequest());
}

//-----------------------------------
// Private methods
//-----------------------------------
private void assertMessagesEquals(ResultActions result, List<Message> messages) throws Exception {
result
.andExpect(content().contentType(APPLICATION_JSON))
.andExpect(jsonPath("$[*].id").value(messages.stream()
.map(Message::getId)
.collect(Collectors.toList())))
.andExpect(jsonPath("$[*].sentFrom").value(messages.stream()
.map(Message::getSentFrom)
.collect(Collectors.toList())))
.andExpect(jsonPath("$[*].sendTo").value(messages.stream()
.map(Message::getSendTo)
.collect(Collectors.toList())))
.andExpect(jsonPath("$[*].content").value(messages.stream()
.map(Message::getContent)
.collect(Collectors.toList())))
.andExpect(jsonPath("$[*].timestamp").isNotEmpty());
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import com.chat.yourway.config.websocket.WebsocketProperties;
import com.chat.yourway.listener.StompSubscriptionListener;
import com.chat.yourway.model.event.ContactEvent;
import com.chat.yourway.service.interfaces.ChatMessageService;
import com.chat.yourway.service.interfaces.ChatNotificationService;
import com.chat.yourway.service.interfaces.ContactEventService;
import java.security.Principal;
Expand Down Expand Up @@ -45,9 +44,6 @@ public class StompSubscriptionListenerTest {
@Mock
private ContactEventService contactEventService;

@Mock
private ChatMessageService chatMessageService;

@Mock
private ChatNotificationService chatNotificationService;

Expand Down Expand Up @@ -94,22 +90,6 @@ public void handleWebSocketSubscribeListener_shouldSaveEvent() {
assertThat(capturedEvent.getLastMessage()).isEqualTo(lastMessage);
}

@Test
public void handleWebSocketSubscribeListener_shouldSendMessageHistory() {
// Given
String email = "[email protected]";
String password = "Password-123";
int topicId = 1;
String destination = "/user/topic/" + topicId;
var event = createSubscribeEvent(destination, getPrincipal(email, password));

// When
stompSubscriptionListener.handleWebSocketSubscribeListener(event);

// Then
verify(chatMessageService, times(1)).sendMessageHistoryByTopicId(topicId, email);
}

@Test
public void handleWebSocketSubscribeListener_shouldNotifyTopicSubscribers() {
// Given
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import com.chat.yourway.dto.request.MessagePrivateRequestDto;
import com.chat.yourway.dto.request.MessagePublicRequestDto;
import com.chat.yourway.dto.request.PageRequestDto;
import com.chat.yourway.dto.response.MessageResponseDto;
import com.chat.yourway.dto.response.TopicResponseDto;
import com.chat.yourway.exception.MessageHasAlreadyReportedException;
Expand All @@ -40,6 +41,9 @@
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.util.ReflectionTestUtils;

@ExtendWith(MockitoExtension.class)
Expand Down Expand Up @@ -246,35 +250,39 @@ public void createPrivate_shouldThrowTopicNotFoundException() {
public void findAllByTopicId_shouldReturnListOfMessages() {
// Given
int topicId = 1;
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.DESC, "timestamp");
PageRequestDto pageRequestDto = new PageRequestDto(0, 10);
List<Message> messages = getPublicMessages();
when(messageRepository.findAllByTopicId(topicId)).thenReturn(messages);
when(messageRepository.findAllByTopicId(topicId, pageable)).thenReturn(messages);

// When
List<MessageResponseDto> result = messageService.findAllByTopicId(topicId);
List<MessageResponseDto> result = messageService.findAllByTopicId(topicId, pageRequestDto);

// Then
assertNotNull(result);
assertEquals(messages.size(), result.size());
for (int i = 0; i < messages.size(); i++) {
assertMessageEquals(messages.get(i), result.get(i));
}
verify(messageRepository, times(1)).findAllByTopicId(topicId);
verify(messageRepository, times(1)).findAllByTopicId(topicId, pageable);
}

@Test
@DisplayName("findAllByTopicId should return empty list")
public void findAllByTopicId_shouldReturnEmptyList() {
// Given
int nonExistentTopicId = 99;
when(messageRepository.findAllByTopicId(nonExistentTopicId)).thenReturn(List.of());
Pageable pageable = PageRequest.of(0, 10, Sort.Direction.DESC, "timestamp");
PageRequestDto pageRequestDto = new PageRequestDto(0, 10);
when(messageRepository.findAllByTopicId(nonExistentTopicId, pageable)).thenReturn(List.of());

// When
List<MessageResponseDto> result = messageService.findAllByTopicId(nonExistentTopicId);
List<MessageResponseDto> result = messageService.findAllByTopicId(nonExistentTopicId, pageRequestDto);

// Then
assertNotNull(result);
assertTrue(result.isEmpty());
verify(messageRepository, times(1)).findAllByTopicId(nonExistentTopicId);
verify(messageRepository, times(1)).findAllByTopicId(nonExistentTopicId, pageable);
}

@Test
Expand Down

0 comments on commit 18b7263

Please sign in to comment.