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

[Test] 투표 마감, 상세 조회 단위 테스트 추가 #187

Merged
merged 5 commits into from
Nov 8, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@
@Service
public class GetVoteDetailService {

private final VoteRepository voteJPARepository;
private final VoteRepository voteRepository;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

private final GetVoteService getVoteService;

public GetVoteDetailResponse getVoteDetail(Long voteId, Long userId) {
// 투표와 옵션리스트 가져오기
VoteEntity vote =
voteJPARepository
.findById(voteId)
.orElseThrow(() -> new NullException("해당 투표가 존재하지 않습니다."));
voteRepository.findById(voteId).orElseThrow(() -> new NullException("해당 투표가 존재하지 않습니다."));

VoteDto voteDto = getVoteService.getVote(vote, userId);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,35 @@ public void createVoteTest_ExceedOptionNum() throws Exception {
.andExpect(jsonPath("$.message").hasJsonPath());
}

@DisplayName("투표 생성 시 옵션이 2개 미만인 경우")
@Test
public void createVoteTest_LackOptionNum() throws Exception {
List<CreateVoteRequest.OptionDto> options = new ArrayList<>();
CreateVoteRequest.OptionDto option1 = new CreateVoteRequest.OptionDto("가라");
options.add(option1);

CreateVoteRequest request = new CreateVoteRequest("군대 가야할까요?", "total", "...", 60, options);

String requestBody = om.writeValueAsString(request);
System.out.println("테스트 : " + requestBody);

// when
ResultActions resultActions =
mvc.perform(
post("/votes")
.header("Authorization", "Bearer " + jwtToken)
.content(requestBody)
.contentType(MediaType.APPLICATION_JSON_VALUE));
// eye
String responseBody = resultActions.andReturn().getResponse().getContentAsString();
System.out.println("테스트 : " + responseBody);

// then
resultActions
.andExpect(status().is4xxClientError())
.andExpect(jsonPath("$.message").hasJsonPath());
}

@DisplayName("투표 생성 시 존재하지 않는 카테고리인 경우")
@Test
public void createVoteTest_CategoryException() throws Exception {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,103 @@
package com.kakao.golajuma.vote.domain.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import com.kakao.golajuma.vote.domain.exception.CloseException;
import com.kakao.golajuma.vote.domain.exception.NullException;
import com.kakao.golajuma.vote.infra.entity.VoteEntity;
import com.kakao.golajuma.vote.infra.repository.VoteRepository;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class CloseVoteServiceTest {
@InjectMocks private CloseVoteService closeVoteService;
@Mock VoteRepository voteRepository;

@DisplayName("존재 하지 않는 투표에 대한 마감 실패")
@DisplayName("투표 마감 정상 응답")
@Test
public void closeVoteTest() {
// given
Long userId = 1L;
Long voteId = 1L;
Long writerId = 1L;
Long requestUserId = 1L;
LocalDateTime date = LocalDateTime.now().plusMinutes(240);
VoteEntity vote = VoteEntity.builder().id(voteId).userId(writerId).voteEndDate(date).build();

// when
when(voteRepository.findById((Long) any())).thenReturn(Optional.of(vote));

closeVoteService.closeVote(voteId, requestUserId);
// 분 단위까지만 비교
LocalDateTime now = LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dTo 바꾸시는거 어떤가요

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

무슨 말씀이시죠??

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이름이 dTo잖아요 저거

LocalDateTime closeDate = vote.getVoteEndDate().truncatedTo(ChronoUnit.MINUTES);

// then
// 현재 시각과 종료된 시각이 일치하는지 검사
assertEquals(now, closeDate);
}

@DisplayName("존재 하지 않는 투표에 대한 마감 실패")
@Test
public void closeVoteTest_notFoundVote() {
// given
Long voteId = -1L;
Long requestUserId = 1L;

// when & then
assertThrows(NullPointerException.class, () -> closeVoteService.closeVote(voteId, userId));
assertThrows(NullException.class, () -> closeVoteService.closeVote(voteId, requestUserId));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 repository를 when then return한 부분이 안보이는거같아요

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

나도 이렇게 했네?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

??/ㅋㅋㅋㅋㅋㅋㅋ

}

@DisplayName("작성자가 아닌 경우 투표에 대한 마감 실패")
@Test
public void closeVoteTest_notWriter() {
// given
Long voteId = 1L;
Long writerId = 1L;
Long requestUserId = 2L;
VoteEntity vote =
VoteEntity.builder()
.id(voteId)
.userId(writerId)
.voteEndDate(LocalDateTime.now().plusMinutes(240))
.build();

// when
when(voteRepository.findById((Long) any())).thenReturn(Optional.of(vote));

// then
assertThrows(CloseException.class, () -> closeVoteService.closeVote(voteId, requestUserId));
}

@DisplayName("이미 완료된 투표인 경우 마감 실패")
@Test
public void closeVoteTest_alreadyComplete() {
// given

Long voteId = 1L;
Long writerId = 1L;
Long requestUserId = 1L;
VoteEntity vote =
VoteEntity.builder()
.id(voteId)
.userId(writerId)
.voteEndDate(LocalDateTime.now().minusMinutes(240))
.build();

// when
when(voteRepository.findById((Long) any())).thenReturn(Optional.of(vote));

// then
assertThrows(CloseException.class, () -> closeVoteService.closeVote(voteId, requestUserId));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.kakao.golajuma.vote.domain.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import com.kakao.golajuma.vote.domain.exception.NullException;
import com.kakao.golajuma.vote.infra.entity.VoteEntity;
import com.kakao.golajuma.vote.infra.repository.VoteRepository;
import com.kakao.golajuma.vote.web.dto.response.GetVoteDetailResponse;
import com.kakao.golajuma.vote.web.dto.response.VoteDto;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class GetVoteDetailServiceTest {
@InjectMocks GetVoteDetailService getVoteDetailService;
@Mock VoteRepository voteRepository;
@Mock GetVoteService getVoteService;
@Mock VoteEntity vote;
@Mock VoteDto voteDto;

@DisplayName("투표 상세 조회 정상 응답")
@Test
public void getVoteDetailTest() {
// when
when(voteRepository.findById((Long) any())).thenReturn(Optional.of(vote));
when(getVoteService.getVote(any(), any())).thenReturn(voteDto);

GetVoteDetailResponse result = getVoteDetailService.getVoteDetail(1L, 1L);

// then
assertEquals(voteDto, result.getVote());
}

@DisplayName("투표 상세 조회 예외 - 존재하지 않는 투표")
@Test
public void getVoteDetailTest_NotFoundVote() {
// when
when(voteRepository.findById((Long) any())).thenThrow(new NullException("message"));

// then
assertThrows(NullException.class, () -> getVoteDetailService.getVoteDetail(0L, 1L));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import com.kakao.golajuma.vote.infra.entity.VoteEntity;
import com.kakao.golajuma.vote.infra.repository.DecisionRepository;
import com.kakao.golajuma.vote.infra.repository.OptionRepository;
import com.kakao.golajuma.vote.web.dto.response.OptionDto;
import com.kakao.golajuma.vote.web.dto.response.VoteDto;
import java.time.LocalDateTime;
import java.util.ArrayList;
Expand Down