Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Test 코드 전체 추가 #106

Merged
merged 2 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions baebae-BE/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ out/
application.yml
application-deploy.yml
application-local.yml
application-test.yml

### fcm ###
baebae-ff525-firebase-adminsdk-zbc8h-7fd10e518b.json
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,21 @@
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@AllArgsConstructor
public class AnswerMapper {
public Answer toEntity(AnswerCreateRequest request, Question question, Member member) {
// Music 엔티티 생성
Music music = Music.builder()
.musicName(request.getMusicName())
.musicSinger(request.getMusicSinger())
.musicAudioUrl(request.getMusicAudioUrl())
.build();
// 요청에서 music 관련 필드가 있는지 확인
Music music = null;
if (request.getMusicName() != null || request.getMusicSinger() != null || request.getMusicAudioUrl() != null) {
// Music 엔티티 생성
music = Music.builder()
.musicName(request.getMusicName())
.musicSinger(request.getMusicSinger())
.musicAudioUrl(request.getMusicAudioUrl())
.build();
}

String senderNickname = question.getNickname();

Expand All @@ -35,11 +38,13 @@ public Answer toEntity(AnswerCreateRequest request, Question question, Member me
.linkAttachments(request.getLinkAttachments())
.profileOnOff(request.getProfileOnOff())
.createdDate(LocalDateTime.now())
.music(music)
.music(music) // music이 null이 아닌 경우 설정
.build();

// Music 엔티티에 Answer 설정
music.setAnswer(answer);
// Music 엔티티에 Answer 설정 (music이 null이 아닌 경우)
if (music != null) {
music.setAnswer(answer);
}

return answer;
}
Expand All @@ -49,7 +54,6 @@ public AnswerDetailResponse toDomain(Answer answer) {
Member member = answer.getMember();
Question question = answer.getQuestion();


return AnswerDetailResponse.of(
answer.getId(),
question.getId(),
Expand All @@ -65,7 +69,6 @@ public AnswerDetailResponse toDomain(Answer answer) {
music != null ? music.getMusicAudioUrl() : null,
answer.getImageFile(),
answer.getCreatedDate()

);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("test")
class BaebaeBeApplicationTests {

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

Expand All @@ -48,6 +50,7 @@

@SpringBootTest
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@WithMockUser
public class AnswerTest {
@Autowired
Expand Down Expand Up @@ -137,7 +140,7 @@ public void createAnswerTest() throws Exception {
when(answerService.createAnswer(any(AnswerCreateRequest.class), eq(1L), any(MockMultipartFile.class)))
.thenReturn(new AnswerDetailResponse(
1L, testQuestion.getId(), testQuestion.getContent(),1L, "이것은 답변입니다.",
testMember.getNickname(), true, "https://link.com", "노래 제목", "가수 이름", "https://audio.url",
testMember.getNickname(), "안녕",true, "https://link.com", "노래 제목", "가수 이름", "https://audio.url",
"https://image.url", LocalDateTime.now()
));

Expand All @@ -163,7 +166,7 @@ public void createAnswerTest() throws Exception {
public void getAllAnswersTest() throws Exception {
AnswerDetailResponse answerDetailResponse = new AnswerDetailResponse(
1L, testQuestion.getId(), testQuestion.getContent(), testMember.getId(),
"이것은 답변입니다.", testMember.getNickname(), true, "https://link.com",
"이것은 답변입니다.", testMember.getNickname(), "안녕", true, "https://link.com",
"노래 제목", "가수 이름", "https://audio.url", "https://image.url", LocalDateTime.now()
);
List<AnswerDetailResponse> answerDetailResponseList = List.of(answerDetailResponse);
Expand Down Expand Up @@ -192,7 +195,7 @@ public void updateAnswerTest() throws Exception {

AnswerDetailResponse answerDetailResponse = new AnswerDetailResponse(
1L, testQuestion.getId(), testQuestion.getContent(), testMember.getId(), "이것은 수정된답변입니다.",
testMember.getNickname(), true, "https://link.com", "노래 제목", "가수 이름", "https://audio.url",
testMember.getNickname(), "안녕",true, "https://link.com", "노래 제목", "가수 이름", "https://audio.url",
"https://image.url", LocalDateTime.now()
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -45,6 +46,7 @@

@SpringBootTest()
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@WithMockUser
@Transactional
public class ManageMemberTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.*;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
Expand All @@ -44,6 +45,7 @@

@SpringBootTest()
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@WithMockUser
@Transactional
public class MemberIntegrationTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

Expand All @@ -34,6 +35,7 @@

@SpringBootTest()
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@WithMockUser
@Transactional
public class NotificationManageTest {
Expand Down Expand Up @@ -114,7 +116,7 @@ void createNotificationTest() throws FirebaseMessagingException {
when(notificationService.createNotification(any(NotificationRequest.create.class)))
.thenAnswer(invocation -> {
NotificationRequest.create request = invocation.getArgument(0);
// Call the Firebase service when creating the notification
// 파이어베이스 호출
mockFirebaseMessagingService.sendNotification(
testMember.getRefreshToken(),
request.getNotificationContent(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,50 +1,60 @@
package com.web.baebaeBE.integration.notification;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.web.baebaeBE.domain.notification.dto.NotificationResponse;
import com.web.baebaeBE.domain.notification.service.NotificationService;
import com.web.baebaeBE.domain.oauth2.controller.Oauth2Controller;
import com.web.baebaeBE.global.jwt.JwtTokenProvider;
import com.web.baebaeBE.domain.notification.entity.Notification;
import com.web.baebaeBE.domain.notification.repository.NotificationRepository;
import com.web.baebaeBE.domain.member.entity.Member;
import com.web.baebaeBE.domain.member.entity.MemberType;
import com.web.baebaeBE.domain.member.repository.MemberRepository;
import com.web.baebaeBE.domain.notification.dto.NotificationRequest;
import java.util.Arrays;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest()
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@WithMockUser
@Transactional
public class NotificationSelectTest {

@Autowired
private MockMvc mockMvc;
@Autowired
@MockBean
private NotificationRepository notificationRepository;
@Autowired
@MockBean
private NotificationService notificationService;
@Autowired
@MockBean
private MemberRepository memberRepository;
@Autowired
private JwtTokenProvider tokenProvider;
@MockBean
private Oauth2Controller oauth2Controller;

private ObjectMapper objectMapper = new ObjectMapper();
private Member testMember;
Expand All @@ -54,18 +64,25 @@ public class NotificationSelectTest {
//각 테스트 전마다 가짜 유저 생성 및 토큰 발급
@BeforeEach
void setup() {
testMember = memberRepository.save(Member.builder()
testMember = Member.builder() // 클래스 필드 testMember를 초기화
.id(1L) // ID를 명시적으로 설정
.email("[email protected]")
.nickname("김예찬")
.nickname("test")
.memberType(MemberType.KAKAO)
.refreshToken("null")
.build());
.build();

accessToken = tokenProvider.generateToken(testMember, Duration.ofDays(1)); // 임시 accessToken 생성
refreshToken = tokenProvider.generateToken(testMember, Duration.ofDays(14)); // 임시 refreshToken 생성
when(memberRepository.save(any(Member.class))).thenReturn(testMember);
when(memberRepository.findByEmail("[email protected]")).thenReturn(Optional.of(testMember));
when(memberRepository.findById(1L)).thenReturn(Optional.of(testMember));

accessToken = tokenProvider.generateToken(testMember, Duration.ofDays(1)); // 임시 accessToken 생성
refreshToken = tokenProvider.generateToken(testMember, Duration.ofDays(14)); // 임시 refreshToken 생성

testMember.updateRefreshToken(refreshToken);
memberRepository.save(testMember);
when(memberRepository.save(testMember)).thenReturn(testMember);

when(memberRepository.findByRefreshToken(refreshToken)).thenReturn(Optional.of(testMember));
}

//각 테스트 후마다 가짜유저 데이터 삭제
Expand All @@ -80,28 +97,33 @@ void tearDown() {
@DisplayName("알림 리스트 조회 테스트(): 해당 유저의 알림 리스트를 조회한다.")
void FindAllNotificationTest() throws Exception{
// given
NotificationRequest.create createRequest1 = new NotificationRequest.create(
testMember.getId(),
"배승우님이 질문을 남기셨습니다! 확인해보세요",
"가은아! 넌 무슨색상을 좋아해?",
NotificationRequest.EventType.NEW_QUESTION,// 이벤트 타입 설정
null
);
NotificationRequest.create createRequest2 = new NotificationRequest.create(
testMember.getId(),
"김예찬님이 질문을 남기셨습니다! 확인해보세요",
"가은아! 너는 무슨음식을 좋아해?",
NotificationRequest.EventType.NEW_QUESTION,// 이벤트 타입 설정
null
);

notificationService.createNotification(createRequest1);
notificationService.createNotification(createRequest2);
Notification notification1 = Notification.builder()
.id(1L)
.member(testMember)
.notificationContent("배승우님이 질문을 남기셨습니다! 확인해보세요")
.detailContent("가은아! 넌 무슨색상을 좋아해?")
.build();

Notification notification2 = Notification.builder()
.id(2L)
.member(testMember)
.notificationContent("김예찬님이 질문을 남기셨습니다! 확인해보세요")
.detailContent("가은아! 너는 무슨음식을 좋아해?")
.build();

List<Notification> notifications = Arrays.asList(notification1, notification2);

List<NotificationResponse.NotificationContentResponse> notificationResponses = notifications.stream()
.map(NotificationResponse.NotificationContentResponse::of)
.collect(Collectors.toList());

when(notificationService.getNotificationsListByMember(testMember.getId()))
.thenReturn(new NotificationResponse.NotificationListResponse(notificationResponses));

// when
mockMvc.perform(get("/api/notifications/member/{memberId}", testMember.getId())
.header("Authorization", "Bearer " + accessToken))
// then
// then
.andExpect(status().isOk())
.andExpect(jsonPath("$.notificationList").exists())
.andExpect(jsonPath("$.notificationList[*].notificationId").exists())
Expand All @@ -110,28 +132,5 @@ void FindAllNotificationTest() throws Exception{
.andExpect(jsonPath("$.notificationList[*].notificationTime").exists());
}


@Test
@DisplayName("단일 알림 조회 테스트(): 해당 알림의 정보를 조회 한다.")
void FindNotificationTest() throws Exception{
// given
NotificationRequest.create createRequest1 = new NotificationRequest.create(
testMember.getId(),
"배승우님이 질문을 남기셨습니다! 확인해보세요",
"가은아! 넌 무슨색상을 좋아해?",
NotificationRequest.EventType.NEW_QUESTION,// 이벤트 타입 설정
null
);
Notification notification = notificationService.createNotification(createRequest1);

// when
mockMvc.perform(get("/api/notifications/{notificationId}", notification.getId())
.header("Authorization", "Bearer " + accessToken))
// then
.andExpect(status().isOk())
.andExpect(jsonPath("$.notificationId").exists())
.andExpect(jsonPath("$.notificationContent").exists())
.andExpect(jsonPath("$.questionContent").exists())
.andExpect(jsonPath("$.notificationTime").exists());
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

Expand All @@ -43,6 +44,7 @@
@SpringBootTest()
@AutoConfigureMockMvc
@WithMockUser
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@Transactional
public class QuestionTest {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

import java.time.Duration;
Expand All @@ -33,6 +35,7 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@AutoConfigureMockMvc
@WithMockUser
public class ReactionCountTest {
Expand Down
Loading
Loading