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

[Weekly/10/Test/Event] Event 테스트(1차) 및 TestData 리펙터링 #77

Merged
merged 1 commit into from
Nov 7, 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
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
package org.ktc2.cokaen.wouldyouin.curation.api.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class LocationFilter {

private Double startLatitude = -90.0;
private Double startLongitude = -180.0;
private Double endLatitude = 90.0;
private Double endLongitude = 180.0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
Expand Down Expand Up @@ -40,10 +42,12 @@ public class EventCreateRequest {
private LocalDateTime endTime;

@NotNull(message = "가격은 필수입니다.")
@Size(min = 0, max = 1000000, message = "가격은 0원 이상 1,000,000원 이하입니다.")
@Min(value = 0, message = "가격은 0원 이상입니다.")
@Max(value = 1000000, message = "가격은 1,000,000원 이하입니다.")
private Integer price;

@Size(min = 0, max = 1000, message = "총 좌석은 0석 이상 1,000석 이하입니다.")
@Min(value = 0, message = "총 좌석은 0석 이상입니다.")
@Max(value = 1000, message = "총 좌석은 1,000석 이하입니다.")
private Integer totalSeat;

@NotNull(message = "카테고리는 필수입니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.FutureOrPresent;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
Expand Down Expand Up @@ -38,10 +40,12 @@ public class EventEditRequest {
private LocalDateTime endTime;

@NotNull(message = "가격은 필수입니다.")
@Size(min = 0, max = 1000000, message = "가격은 0원 이상 1,000,000원 이하입니다.")
@Min(value = 0, message = "가격은 0원 이상입니다.")
@Max(value = 1000000, message = "가격은 1,000,000원 이하입니다.")
private Integer price;

@Size(min = 0, max = 1000, message = "총 좌석은 0석 이상 1,000석 이하입니다.")
@Min(value = 0, message = "총 좌석은 0석 이상입니다.")
@Max(value = 1000, message = "총 좌석은 1,000석 이하입니다.")
private Integer totalSeat;

@NotNull(message = "카테고리는 필수입니다.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public EventSliceResponse getAllByHostIdOrderByCreatedDateDesc(Long hostId, Page

private EventSliceResponse getEventSliceResponse(Slice<Event> eventSlice, Long lastId) {
List<EventResponse> events = eventSlice.stream().map(EventResponse::from).toList();
if (!eventSlice.hasContent()) {
if (eventSlice.hasContent()) {
Long id = eventSlice.getContent().getLast().getId();
return EventSliceResponse.of(events, eventSlice.getSize(), id);
}
Expand All @@ -73,11 +73,10 @@ public EventResponse create(Long hostId, EventCreateRequest eventCreateRequest)
}

private void validateHostId(Long hostId, Event event) {
if (!hostId.equals(event.getId())) {
if (!hostId.equals(event.getHost().getId())) {
throw new UnauthorizedException("Host");
}
}

@Transactional
public EventResponse update(Long hostId, Long eventId, EventEditRequest eventEditRequest) {
Event event = getByIdOrThrow(eventId);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,67 +1,81 @@
package org.ktc2.cokaen.wouldyouin.event;


import static java.lang.Math.abs;
import static org.ktc2.cokaen.wouldyouin.global.TestData.MemberDomain.createValidHost;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;
import static org.mockito.Mockito.times;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.util.Random;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import org.ktc2.cokaen.wouldyouin._common.vo.Area;
import org.ktc2.cokaen.wouldyouin._common.vo.Category;
import org.ktc2.cokaen.wouldyouin._common.vo.Location;
import org.ktc2.cokaen.wouldyouin.auth.application.JwtAuthFilter;
import org.ktc2.cokaen.wouldyouin.auth.application.JwtService;
import org.ktc2.cokaen.wouldyouin.curation.api.dto.LocationFilter;
import org.ktc2.cokaen.wouldyouin.event.api.EventController;
import org.ktc2.cokaen.wouldyouin.event.api.dto.EventCreateRequest;
import org.ktc2.cokaen.wouldyouin.event.api.dto.EventEditRequest;
import org.ktc2.cokaen.wouldyouin.event.api.dto.EventSliceResponse;
import org.ktc2.cokaen.wouldyouin.event.application.EventService;
import org.ktc2.cokaen.wouldyouin.global.TestData;
import org.ktc2.cokaen.wouldyouin.global.TestData.EventDomain;
import org.ktc2.cokaen.wouldyouin.global.mockMember.WithMockHost;
import org.ktc2.cokaen.wouldyouin.member.application.MemberService;
import org.ktc2.cokaen.wouldyouin.member.persist.Host;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@WithMockUser(username = "user", roles = {"USER"})
@WebMvcTest(EventController.class)
class EventControllerUnitTest {

private static Long id;
private static Host validHost;
private static ObjectMapper objectMapper;
@MockBean
private EventService eventService;

@MockBean
private MemberService memberService;

@MockBean
private JwtService jwtService;

@MockBean
private JwtAuthFilter jwtAuthFilter;

@MockBean
private EventSliceResponse eventSliceResponse;
@Autowired
private MockMvc mockMvc;

@Autowired
private WebApplicationContext context;

private static Long id;

private static ObjectMapper objectMapper;
@BeforeAll
public static void init() {
id = 3L;
validHost = createValidHost();
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
}

@BeforeEach
public void setup() throws Exception {
Expand All @@ -71,62 +85,140 @@ public void setup() throws Exception {
.build();
}

@BeforeAll
public static void init() {
id = abs(new Random().nextLong());
objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
}

@Test
@DisplayName("모든 행사 조회 - 성공")
@WithMockHost
void getEventsByFilterOrderByDistanceAsc() throws Exception {
mockMvc.perform(get("/api/events")).andExpect(status().isOk());
verify(eventService).getAllByFilterOrderByDistanceAsc();
// given
LocationFilter locationFilter = new LocationFilter(0.0, 0.0, 10.0, 10.0);
Location currentLocation = new Location(3.0, 2.0);
Category category = Category.공예;
Area area = Area.광주;
int pageNumber = 1; // 교수님
int pageSize = 10; //
Long lastId = 1L;
Pageable pageable = PageRequest.of(pageNumber, pageSize);

given(eventService.getAllByFilterOrderByDistanceAsc(
locationFilter,
currentLocation,
category,
area,
pageable,
lastId))
.willReturn(eventSliceResponse);

// when
mockMvc.perform(get("/api/events")
.param("startLatitude", locationFilter.getStartLatitude().toString())
.param("startLongitude", locationFilter.getStartLongitude().toString())
.param("endLatitude", locationFilter.getEndLatitude().toString())
.param("endLongitude", locationFilter.getEndLongitude().toString())
.param("latitude", currentLocation.getLatitude().toString())
.param("longitude", currentLocation.getLongitude().toString())
.param("category", category.toString()) // enum을 문자열로 변환하여 설정
.param("area", area.toString()) // enum을 문자열로 변환하여 설정
.param("page", String.valueOf(pageNumber))
.param("size", String.valueOf(pageSize))
.param("lastId", String.valueOf(lastId))
).andDo(print())
.andExpect(status().isOk());

// then
then(eventService).should(times(1)).getAllByFilterOrderByDistanceAsc(
any(LocationFilter.class),
any(Location.class),
eq(category),
eq(area),
eq(pageable),
eq(lastId)
);
}

@Test
@DisplayName("주최자 id를 통한 모든 행사 조회 - 성공")
@WithMockHost
void getEventsByLocationByHostId() throws Exception {
mockMvc.perform(get("/api/events/hosts/" + id)).andExpect(status().isOk());
verify(eventService).getAllByHostIdOrderByCreatedDateDesc(id);
// given
int pageNumber = 1;
int pageSize = 10;
Pageable pageable = PageRequest.of(pageNumber, pageSize);
Long lastId = 1L;

// when
mockMvc.perform(get("/api/events/hosts/" + id)
.param("page", String.valueOf(pageNumber))
.param("size", String.valueOf(pageSize))
.param("lastId", String.valueOf(lastId))
)
.andExpect(status().isOk());

//then
then(eventService).should(times(1)).getAllByHostIdOrderByCreatedDateDesc(
eq(id),
eq(pageable),
eq(lastId)
);
}

@Test
@DisplayName("행사 id를 통한 행사 조회 - 성공")
@WithMockHost
void getEventByEventId() throws Exception {
mockMvc.perform(get("/api/events/" + id)).andExpect(status().isOk());
verify(eventService).getById(id);
//given
//when
mockMvc.perform(get("/api/events/" + id))
.andDo(print())
.andExpect(status().isOk());

//then
then(eventService).should(times(1)).getById(eq(id));
}

@Test
@DisplayName("행사 생성 - 성공")
@WithMockHost
void createEvent() throws Exception {
//given
//when
mockMvc.perform(post("/api/events")
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(TestData.validEventCreateRequest)))
.content(objectMapper.writeValueAsString(EventDomain.createValidEventCreateRequest())))
.andDo(print())
.andExpect(status().isCreated());
verify(eventService).create(any(EventCreateRequest.class));

//then
then(eventService).should(times(1)).create(eq(id), any(EventCreateRequest.class));
}

@Test
@DisplayName("행사 수정 - 성공")
@WithMockHost
void updateEvent() throws Exception {
//given
//when
mockMvc.perform(put("/api/events/" + id)
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(TestData.validEventCreateRequest)))
.content(objectMapper.writeValueAsString(EventDomain.createValidEventCreateRequest())))
.andExpect(status().isOk());
verify(eventService).update(eq(id), any(EventEditRequest.class));

//then
then(eventService).should(times(1)).update(eq(id), eq(id), any(EventEditRequest.class));
}

@Test
@DisplayName("행사 삭제 - 성공")
@WithMockHost
void deleteEvent() throws Exception {
//given
//when
mockMvc.perform(delete("/api/events/" + id)
.with(csrf())
).andExpect(status().isNoContent());
verify(eventService).delete(id);

//then
then(eventService).should(times(1)).delete(eq(id), eq(id));
}
}
Loading
Loading