Skip to content

Commit

Permalink
Merge pull request #150 from softeerbootcamp4th/test/#142-lottery-test
Browse files Browse the repository at this point in the history
Test/#142 lottery test
  • Loading branch information
wjddn2165 authored Aug 16, 2024
2 parents f87b7c9 + 1ec3fef commit 0eb1764
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,4 @@ public ResponseEntity<List<CasperBotResponseDto>> getCasperBots() {
return ResponseEntity.status(HttpStatus.OK)
.body(redisService.getRecentData());
}

// 캐스퍼 봇 조회 API
@GetMapping("/{casperId}")
public ResponseEntity<CasperBotResponseDto> getCasperBot(@PathVariable String casperId) {
return ResponseEntity
.status(HttpStatus.OK)
.body(lotteryEventService.getCasperBot(Long.parseLong(casperId)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,13 @@
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;

@Getter
@Builder
@EqualsAndHashCode
public class CasperBotRequestDto {

@NotNull(message = "눈 모양 값은 필수 필드입니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
import JGS.CasperEvent.global.enums.Role;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*;
import lombok.EqualsAndHashCode;
import lombok.Getter;

@Getter
@Entity
@EqualsAndHashCode(callSuper = false)
@Inheritance(strategy = InheritanceType.JOINED)
public class BaseUser extends BaseEntity {
@Id
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
package JGS.CasperEvent.domain.event.controller.eventController;

import JGS.CasperEvent.domain.event.dto.RequestDto.lotteryEventDto.CasperBotRequestDto;
import JGS.CasperEvent.domain.event.dto.ResponseDto.lotteryEventResponseDto.CasperBotResponseDto;
import JGS.CasperEvent.domain.event.dto.ResponseDto.lotteryEventResponseDto.LotteryEventResponseDto;
import JGS.CasperEvent.domain.event.dto.ResponseDto.lotteryEventResponseDto.LotteryParticipantResponseDto;
import JGS.CasperEvent.domain.event.entity.casperBot.CasperBot;
import JGS.CasperEvent.domain.event.entity.participants.LotteryParticipants;
import JGS.CasperEvent.domain.event.service.adminService.AdminService;
import JGS.CasperEvent.domain.event.service.eventService.LotteryEventService;
import JGS.CasperEvent.domain.event.service.redisService.RedisService;
import JGS.CasperEvent.global.entity.BaseUser;
import JGS.CasperEvent.global.enums.Role;
import JGS.CasperEvent.global.jwt.service.UserService;
import JGS.CasperEvent.global.jwt.util.JwtProvider;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
Expand All @@ -22,8 +27,9 @@

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Expand All @@ -36,6 +42,8 @@
public class LotteryEventControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;

@MockBean
private LotteryEventService lotteryEventService;
Expand All @@ -46,53 +54,57 @@ public class LotteryEventControllerTest {
@MockBean
private RedisService redisService;

public String phoneNumber;
public String accessToken;
private BaseUser user;
private String phoneNumber;
private String accessToken;
private CasperBot casperBot;
private CasperBotRequestDto casperBotRequest;
private CasperBotResponseDto casperBotResponse;
private LotteryParticipants lotteryParticipants;
private LotteryEventResponseDto lotteryEventResponseDto;

@BeforeEach
void setUp() throws Exception {
this.phoneNumber = "010-0000-0000";

// 베이스 유저 생성
user = new BaseUser(this.phoneNumber, Role.USER);
// 추첨 이벤트 참여자
lotteryParticipants = new LotteryParticipants(user);
// userService 모킹
given(userService.verifyUser(any())).willReturn(new BaseUser(this.phoneNumber, Role.USER));
given(userService.verifyUser(any())).willReturn(user);

// 엑세스 토큰 설정
this.accessToken = getToken(this.phoneNumber);

// 추첨 이벤트 조회
LotteryEventResponseDto lotteryEventResponseDto = new LotteryEventResponseDto(
lotteryEventResponseDto = new LotteryEventResponseDto(
LocalDateTime.of(2024, 8, 15, 0, 0, 0),
LocalDateTime.of(2024, 8, 1, 0, 0, 0),
LocalDateTime.of(2024, 8, 31, 0, 0, 0),
ChronoUnit.DAYS.between(LocalDateTime.of(2024, 8, 1, 0, 0, 0), LocalDateTime.of(2024, 8, 31, 0, 0, 0))
);
given(lotteryEventService.getLotteryEvent()).willReturn(lotteryEventResponseDto);
}

String getToken(String phoneNumber) throws Exception {
String requestBody = String.format("""
{
"phoneNumber": "%s"
}
""", phoneNumber);

ResultActions perform = mockMvc.perform(post("/event/auth")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody));
casperBotRequest = CasperBotRequestDto.builder()
.eyeShape(0)
.eyePosition(0)
.mouthShape(0)
.color(0)
.sticker(0)
.name("name")
.expectation("expectation")
.referralId("QEszP1K8IqcapUHAVwikXA==").build();

String jsonString = perform.andReturn().getResponse().getContentAsString();
String tokenPrefix = "\"accessToken\":\"";
int start = jsonString.indexOf(tokenPrefix) + tokenPrefix.length();
int end = jsonString.indexOf("\"", start);
casperBot = new CasperBot(casperBotRequest, "010-0000-0000");

return "Bearer " + jsonString.substring(start, end);
casperBotResponse = CasperBotResponseDto.of(casperBot);
}

@Test
@DisplayName("추첨 이벤트 조회 API 성공 테스트")
void getLotteryEventAndServerTime() throws Exception {
//given
String token = this.accessToken;
given(lotteryEventService.getLotteryEvent()).willReturn(lotteryEventResponseDto);

//when
ResultActions perform = mockMvc.perform(get("/event/lottery")
Expand All @@ -104,6 +116,100 @@ void getLotteryEventAndServerTime() throws Exception {
.andExpect(jsonPath("$.eventStartDate").value("2024-08-01T00:00:00"))
.andExpect(jsonPath("$.eventEndDate").value("2024-08-31T00:00:00"))
.andDo(print());
}

@Test
@DisplayName("캐스퍼 봇 생성 API 성공 테스트")
void postCasperBot() throws Exception {
//given
String requestBody = objectMapper.writeValueAsString(casperBotRequest);
given(lotteryEventService.postCasperBot(user, casperBotRequest))
.willReturn(CasperBotResponseDto.of(casperBot));

//when
ResultActions perform = mockMvc.perform(post("/event/lottery/casperBot")
.header("Authorization", accessToken)
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody));

//then
perform.andExpect(status().isCreated())
.andExpect(jsonPath("$.eyeShape").value(0))
.andExpect(jsonPath("$.eyePosition").value(0))
.andExpect(jsonPath("$.mouthShape").value(0))
.andExpect(jsonPath("$.color").value(0))
.andExpect(jsonPath("$.sticker").value(0))
.andExpect(jsonPath("$.name").value("name"))
.andExpect(jsonPath("$.expectation").value("expectation"))
.andDo(print());
}

@Test
@DisplayName("응모 여부 조회 성공 테스트")
void GetLotteryParticipantsSuccessTest() throws Exception {
//given
given(lotteryEventService.getLotteryParticipant(user))
.willReturn(LotteryParticipantResponseDto.of(lotteryParticipants, casperBotResponse));

//when
ResultActions perform = mockMvc.perform(get("/event/lottery/applied")
.header("Authorization", accessToken)
.contentType(MediaType.APPLICATION_JSON));

//then
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.linkClickedCount").value(0))
.andExpect(jsonPath("$.expectations").value(0))
.andExpect(jsonPath("$.appliedCount").value(1))
.andExpect(jsonPath("$.casperBot.eyeShape").value(0))
.andExpect(jsonPath("$.casperBot.eyePosition").value(0))
.andExpect(jsonPath("$.casperBot.mouthShape").value(0))
.andExpect(jsonPath("$.casperBot.color").value(0))
.andExpect(jsonPath("$.casperBot.sticker").value(0))
.andExpect(jsonPath("$.casperBot.name").value("name"))
.andExpect(jsonPath("$.casperBot.expectation").value("expectation"))
.andDo(print());
}

@Test
@DisplayName("최근 100개 캐스퍼 봇 조회 성공 테스트")
void getCasperBotsSuccessTest() throws Exception {
//given
List<CasperBotResponseDto> recentData = new ArrayList<>();
for (int i = 0; i < 100; i++) {
recentData.add(casperBotResponse);
}
given(redisService.getRecentData())
.willReturn(recentData);

//when
ResultActions perform = mockMvc.perform(get("/event/lottery/caspers")
.header("Authorization", accessToken)
.contentType(MediaType.APPLICATION_JSON));

//then
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(100))
.andDo(print());

}

String getToken(String phoneNumber) throws Exception {
String requestBody = String.format("""
{
"phoneNumber": "%s"
}
""", phoneNumber);

ResultActions perform = mockMvc.perform(post("/event/auth")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody));

String jsonString = perform.andReturn().getResponse().getContentAsString();
String tokenPrefix = "\"accessToken\":\"";
int start = jsonString.indexOf(tokenPrefix) + tokenPrefix.length();
int end = jsonString.indexOf("\"", start);

return "Bearer " + jsonString.substring(start, end);
}
}

0 comments on commit 0eb1764

Please sign in to comment.