update test file

This commit is contained in:
shinmj
2021-10-28 10:52:11 +09:00
parent f0fe0ed6ff
commit c03f875162
20 changed files with 1057 additions and 398 deletions

View File

@@ -113,7 +113,6 @@ public class ReserveItemApiController {
@GetMapping("/api/v1/reserve-items/{reserveItemId}")
@ResponseStatus(HttpStatus.OK)
public Mono<ReserveItemResponseDto> findById(@PathVariable Long reserveItemId) {
System.out.println("findById : " + reserveItemId);
return reserveItemService.findById(reserveItemId);
}
@@ -177,7 +176,6 @@ public class ReserveItemApiController {
@PutMapping("/api/v1/reserve-items/{reserveItemId}/inventories")
@ResponseStatus(HttpStatus.OK)
public Mono<Boolean> updateInventory(@PathVariable Long reserveItemId, @RequestBody Integer reserveQty) {
System.out.println("update inventories : " + reserveItemId+" : " + reserveQty);
return reserveItemService.updateInventory(reserveItemId, reserveQty);
}

View File

@@ -1,5 +1,6 @@
package org.egovframe.cloud.reserveitemservice.api.reserveItem.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
@@ -92,6 +93,43 @@ public class ReserveItemSaveRequestDto {
@Size(max = 50)
private String managerContact; //담당자 연락처
@Builder
public ReserveItemSaveRequestDto(String reserveItemName, Long locationId, String categoryId, Integer totalQty,
Integer inventoryQty, LocalDateTime operationStartDate, LocalDateTime operationEndDate,
String reserveMethodId, String reserveMeansId, LocalDateTime requestStartDate,
LocalDateTime requestEndDate, Boolean isPeriod, Integer periodMaxCount, String externalUrl,
String selectionMeansId, Boolean isPaid, BigDecimal usageCost, Boolean isUse, String purpose,
String address, String targetId, String excluded, String homepage, String contact, String managerDept,
String managerName, String managerContact) {
this.reserveItemName = reserveItemName;
this.locationId = locationId;
this.categoryId = categoryId;
this.totalQty = totalQty;
this.inventoryQty = inventoryQty;
this.operationStartDate = operationStartDate;
this.operationEndDate = operationEndDate;
this.reserveMethodId = reserveMethodId;
this.reserveMeansId = reserveMeansId;
this.requestStartDate = requestStartDate;
this.requestEndDate = requestEndDate;
this.isPeriod = isPeriod;
this.periodMaxCount = periodMaxCount;
this.externalUrl = externalUrl;
this.selectionMeansId = selectionMeansId;
this.isPaid = isPaid;
this.usageCost = usageCost;
this.isUse = isUse;
this.purpose = purpose;
this.address = address;
this.targetId = targetId;
this.excluded = excluded;
this.homepage = homepage;
this.contact = contact;
this.managerDept = managerDept;
this.managerName = managerName;
this.managerContact = managerContact;
}
public ReserveItem toEntity() {
return ReserveItem.builder()
.reserveItemName(this.reserveItemName)

View File

@@ -1,5 +1,6 @@
package org.egovframe.cloud.reserveitemservice.api.reserveItem.dto;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
@@ -61,7 +62,6 @@ public class ReserveItemUpdateRequestDto {
private String externalUrl; //외부링크
@NotBlank
private String selectionMeansId; //선별 방법 - 공통코드 reserve-selection
@NotNull
private Boolean isPaid; // 유/무료 - false: 무료, true: 유료
private BigDecimal usageCost; //이용 요금
private Boolean isUse; //사용여부
@@ -83,6 +83,43 @@ public class ReserveItemUpdateRequestDto {
@Size(max = 50)
private String managerContact; //담당자 연락처
@Builder
public ReserveItemUpdateRequestDto(String reserveItemName, Long locationId, String categoryId,
Integer totalQty, Integer inventoryQty, LocalDateTime operationStartDate, LocalDateTime operationEndDate,
String reserveMethodId, String reserveMeansId, LocalDateTime requestStartDate,
LocalDateTime requestEndDate, Boolean isPeriod, Integer periodMaxCount, String externalUrl,
String selectionMeansId, Boolean isPaid, BigDecimal usageCost, Boolean isUse, String purpose,
String address, String targetId, String excluded, String homepage, String contact, String managerDept,
String managerName, String managerContact) {
this.reserveItemName = reserveItemName;
this.locationId = locationId;
this.categoryId = categoryId;
this.totalQty = totalQty;
this.inventoryQty = inventoryQty;
this.operationStartDate = operationStartDate;
this.operationEndDate = operationEndDate;
this.reserveMethodId = reserveMethodId;
this.reserveMeansId = reserveMeansId;
this.requestStartDate = requestStartDate;
this.requestEndDate = requestEndDate;
this.isPeriod = isPeriod;
this.periodMaxCount = periodMaxCount;
this.externalUrl = externalUrl;
this.selectionMeansId = selectionMeansId;
this.isPaid = isPaid;
this.usageCost = usageCost;
this.isUse = isUse;
this.purpose = purpose;
this.address = address;
this.targetId = targetId;
this.excluded = excluded;
this.homepage = homepage;
this.contact = contact;
this.managerDept = managerDept;
this.managerName = managerName;
this.managerContact = managerContact;
}
public ReserveItem toEntity() {
return ReserveItem.builder()
.reserveItemName(this.reserveItemName)

View File

@@ -278,7 +278,6 @@ public class ReserveItem extends BaseEntity {
* @return
*/
public ReserveItem update(ReserveItemUpdateRequestDto updateRequestDto) {
System.out.println("============ ?? : " + updateRequestDto.toString());
this.reserveItemName = updateRequestDto.getReserveItemName();
this.locationId = updateRequestDto.getLocationId();
this.categoryId = updateRequestDto.getCategoryId();

View File

@@ -235,7 +235,6 @@ public class ReserveItemRepositoryImpl implements ReserveItemRepositoryCustom{
whereCriteria.add(where("use_at").isTrue());
whereCriteria.add(where("reserve_method_id").is("internet"));
}
System.out.println(whereCriteria.toString());
return whereCriteria;
}

View File

@@ -1,144 +1,183 @@
package org.egovframe.cloud.reserveitemservice.api.location;
import static org.junit.jupiter.api.Assertions.*;
import org.egovframe.cloud.reserveitemservice.api.location.dto.LocationSaveRequestDto;
import org.egovframe.cloud.reserveitemservice.api.location.dto.LocationUpdateRequestDto;
import org.egovframe.cloud.reserveitemservice.config.R2dbcConfig;
import org.egovframe.cloud.reserveitemservice.domain.location.Location;
import org.egovframe.cloud.reserveitemservice.domain.location.LocationRepository;
import org.junit.jupiter.api.BeforeEach;
import org.egovframe.cloud.reserveitemservice.domain.reserveItem.ReserveItem;
import org.egovframe.cloud.reserveitemservice.domain.reserveItem.ReserveItemRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.BDDMockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.reactive.function.BodyInserters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableConfigurationProperties
@TestPropertySource(properties = {"spring.config.location=classpath:application-test.yml"})
@ActiveProfiles("test")
@Import({R2dbcConfig.class})
class LocationApiControllerTest {
public class LocationApiControllerTest {
@MockBean
private LocationRepository locationRepository;
@Autowired
private LocationRepository locationRepository;
@Autowired
private WebTestClient webTestClient;
@Autowired
private ReserveItemRepository reserveItemRepository;
private final static String API_URL = "/api/v1/locations";
@Autowired
WebTestClient webTestClient;
private Location location = Location.builder()
.locationId(1L)
.locationName("location")
.isUse(true)
.sortSeq(1)
.build();
private static final String API_URL = "/api/v1/locations";
@BeforeEach
public void setup() {
BDDMockito.when(locationRepository.findById(ArgumentMatchers.anyLong()))
.thenReturn(Mono.just(location));
//조회조건 있는 경우
BDDMockito.when(locationRepository.findAllByLocationNameContainingOrderBySortSeq(
ArgumentMatchers.anyString(), ArgumentMatchers.any(Pageable.class)))
.thenReturn(Flux.just(location));
BDDMockito.when(locationRepository.countAllByLocationNameContaining(ArgumentMatchers.anyString()))
.thenReturn(Mono.just(1L));
//조회조건 없는 경우
BDDMockito.when(locationRepository.findAllByOrderBySortSeq(ArgumentMatchers.any(Pageable.class)))
.thenReturn(Flux.just(location));
BDDMockito.when(locationRepository.count()).thenReturn(Mono.just(1L));
@AfterEach
public void tearDown() {
reserveItemRepository.deleteAll().block();
locationRepository.deleteAll().block();
}
BDDMockito.when(locationRepository.save(ArgumentMatchers.any(Location.class)))
.thenReturn(Mono.just(location));
@Test
public void 한건조회_성공() throws Exception {
}
Location location1 = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location1);
@Test
public void 한건조회_성공() throws Exception {
webTestClient.get()
.uri(API_URL+"/{locationId}", location.getLocationId())
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.locationName").isEqualTo(location.getLocationName());
}
@Test
public void 조회조건있는경우_페이지목록조회_성공() throws Exception {
webTestClient.get()
.uri(API_URL+"?keywordType=locationName&keyword=location&page=0&size=3")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.totalElements").isEqualTo(1)
.jsonPath("$.content[0].locationName").isEqualTo(location.getLocationName());
}
@Test
public void 조회조건없는경우_페이지목록조회_성공() throws Exception {
webTestClient.get()
.uri(API_URL+"?page=0&size=3")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.totalElements").isEqualTo(1)
.jsonPath("$.content[0].locationName").isEqualTo(location.getLocationName());
}
@Test
public void 한건저장_성공() throws Exception {
webTestClient.post()
.uri(API_URL)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(LocationSaveRequestDto.builder()
.locationName(location.getLocationName())
.isUse(location.getIsUse())
.sortSeq(location.getSortSeq())
.build()))
.exchange()
.expectStatus().isCreated()
.expectBody().jsonPath("$.locationName").isEqualTo(location.getLocationName());
}
@Test
public void 한건수정_성공() throws Exception {
webTestClient.put()
.uri(API_URL+"/{locationId}", location.getLocationId())
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(LocationUpdateRequestDto.builder()
.locationName("updateLocation")
.isUse(location.getIsUse())
.sortSeq(location.getSortSeq())
.build()))
.exchange()
.expectStatus().isNoContent();
}
@Test
public void 한건삭제_참조데이터존재_삭제실패() throws Exception {
BDDMockito.when(locationRepository.delete(ArgumentMatchers.any(Location.class)))
.thenReturn(Mono.error(new DataIntegrityViolationException("integrity test")));
webTestClient.delete()
.uri(API_URL+"/{locationId}", 1L)
.exchange()
.expectStatus().isBadRequest();
}
webTestClient.get()
.uri(API_URL+"/{locationId}", location1.getLocationId())
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.locationName").isEqualTo(location1.getLocationName());
}
}
@Test
public void 조회조건있는경우_페이지목록조회_성공() throws Exception {
Location location1 = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location1);
webTestClient.get()
.uri(API_URL+"?keywordType=locationName&keyword=location&page=0&size=3")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.totalElements").isEqualTo(1)
.jsonPath("$.content[0].locationName").isEqualTo(location1.getLocationName());
}
@Test
public void 조회조건없는경우_페이지목록조회_성공() throws Exception {
Location location1 = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location1);
webTestClient.get()
.uri(API_URL+"?page=0&size=3")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.totalElements").isEqualTo(1)
.jsonPath("$.content[0].locationName").isEqualTo(location1.getLocationName());
}
@Test
public void 한건저장_성공() throws Exception {
webTestClient.post()
.uri(API_URL)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(LocationSaveRequestDto.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()))
.exchange()
.expectStatus().isCreated()
.expectBody().jsonPath("$.locationName").isEqualTo("location1");
}
@Test
public void 한건수정_성공() throws Exception {
Location location1 = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location1);
webTestClient.put()
.uri(API_URL+"/{locationId}", location1.getLocationId())
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(LocationUpdateRequestDto.builder()
.locationName("updateLocation")
.isUse(location1.getIsUse())
.sortSeq(location1.getSortSeq())
.build()))
.exchange()
.expectStatus().isNoContent();
Location updatedLocation = locationRepository.findById(location1.getLocationId()).block();
assertNotNull(updatedLocation);
assertEquals(updatedLocation.getLocationName(), "updateLocation");
}
@Test
public void 한건삭제_참조데이터존재_삭제실패() throws Exception {
Location location1 = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location1);
reserveItemRepository.save(ReserveItem.builder()
.locationId(location1.getLocationId())
.categoryId("test")
.build()).block();
webTestClient.delete()
.uri(API_URL+"/{locationId}", location1.getLocationId())
.exchange()
.expectStatus().isBadRequest();
}
@Test
public void 한건삭제_성공() throws Exception {
Location location1 = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location1);
webTestClient.delete()
.uri(API_URL+"/{locationId}", location1.getLocationId())
.exchange()
.expectStatus().isNoContent();
}
}

View File

@@ -1,14 +1,30 @@
package org.egovframe.cloud.reserveitemservice.api.reserveItem;
import static org.assertj.core.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.*;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.egovframe.cloud.common.exception.dto.ErrorCode;
import org.egovframe.cloud.common.exception.dto.ErrorResponse;
import org.egovframe.cloud.reserveitemservice.api.reserveItem.dto.ReserveItemMainResponseDto;
import org.egovframe.cloud.reserveitemservice.api.reserveItem.dto.ReserveItemRequestDto;
import org.egovframe.cloud.reserveitemservice.api.reserveItem.dto.ReserveItemResponseDto;
import org.egovframe.cloud.reserveitemservice.api.reserveItem.dto.ReserveItemSaveRequestDto;
import org.egovframe.cloud.reserveitemservice.api.reserveItem.dto.ReserveItemUpdateRequestDto;
import org.egovframe.cloud.reserveitemservice.config.R2dbcConfig;
import org.egovframe.cloud.reserveitemservice.domain.code.Code;
import org.egovframe.cloud.reserveitemservice.domain.location.Location;
import org.egovframe.cloud.reserveitemservice.domain.location.LocationRepository;
import org.egovframe.cloud.reserveitemservice.domain.reserveItem.ReserveItem;
import org.egovframe.cloud.reserveitemservice.domain.reserveItem.ReserveItemRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.BDDMockito;
@@ -17,7 +33,10 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Import;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.data.domain.Pageable;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.reactive.server.WebTestClient;
@@ -29,136 +48,243 @@ import reactor.core.publisher.Mono;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableConfigurationProperties
@TestPropertySource(properties = {"spring.config.location=classpath:application-test.yml"})
@ActiveProfiles(profiles = "test")
@ActiveProfiles("test")
@Import({R2dbcConfig.class})
class ReserveItemApiControllerTest {
@Autowired
private LocationRepository locationRepository;
@MockBean
ReserveItemRepository reserveItemRepository;
@Autowired
private ReserveItemRepository reserveItemRepository;
@Autowired
private R2dbcEntityTemplate entityTemplate;
@Autowired
WebTestClient webTestClient;
private final static String API_URL = "/api/v1/reserve-items";
Code category = null;
Location location = null;
ReserveItem reserveItem = ReserveItem.builder().build();
@AfterEach
public void tearDown() {
entityTemplate.delete(Code.class).all().block();
reserveItemRepository.deleteAll().block();
locationRepository.deleteAll().block();
}
@BeforeEach
public void setUp() {
category = Code.builder().codeName("category").codeId("category").parentCodeId("reserve-category").build();
entityTemplate.insert(Code.class)
.using(category).block();
location = locationRepository.save(Location.builder()
.locationName("location1")
.isUse(true)
.sortSeq(1)
.build()).block();
assertNotNull(location);
reserveItem = ReserveItem.builder()
.categoryId(category.getCodeId())
.locationId(location.getLocationId())
.reserveItemName("test")
.isUse(Boolean.TRUE)
.operationStartDate(LocalDateTime.of(2021, 10, 1, 1, 1))
.operationEndDate(LocalDateTime.of(2021, 10, 31, 23, 59))
.reserveMethodId("internet")
.reserveMeansId("realtime")
.requestStartDate(LocalDateTime.of(2021, 10, 1, 1, 1))
.requestEndDate(LocalDateTime.of(2021, 10, 31, 23, 59))
.totalQty(100)
.inventoryQty(100)
.isPeriod(Boolean.FALSE)
.selectionMeansId("evaluate")
.build();
}
@Test
public void 사용자별_검색_목록_조회_성공() throws Exception {
LocalDateTime startDate = LocalDateTime.of(2021, 1, 28, 1,1);
LocalDateTime endDate = LocalDateTime.of(2021, 12, 6, 1,1);
public void 사용자목록조회_성공() throws Exception {
Location location = Location.builder()
.locationId(1L)
.locationName("location")
.sortSeq(1)
.isUse(true)
.build();
ReserveItem reserveItem = ReserveItem.builder()
.reserveItemId(1L)
.location(location)
.locationId(location.getLocationId())
.reserveItemName("test")
.categoryId("education")
.categoryName("교육")
.totalQty(100)
.inventoryQty(80)
.operationEndDate(endDate)
.operationStartDate(startDate)
.isPeriod(false)
.isUse(true)
.build();
ReserveItem saved = reserveItemRepository.save(reserveItem).block();
assertNotNull(saved);
BDDMockito.when(reserveItemRepository.searchForUser(ArgumentMatchers.anyString(),
ArgumentMatchers.any(ReserveItemRequestDto.class), ArgumentMatchers.any(Pageable.class)))
.thenReturn(Flux.just(reserveItem));
webTestClient.method(HttpMethod.GET)
.uri("/api/v1/"+category.getCodeId()+"/reserve-items"+"?page=0&size=3&isUse=true")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.totalElements").isEqualTo(1)
.jsonPath("$.content[0].reserveItemName").isEqualTo(reserveItem.getReserveItemName());
}
BDDMockito.when(reserveItemRepository.searchCountForUser(ArgumentMatchers.anyString(),
ArgumentMatchers.any(ReserveItemRequestDto.class), ArgumentMatchers.any(Pageable.class)))
.thenReturn(Mono.just(1L));
@Test
public void 관리자목록조회_성공() throws Exception {
webTestClient.get()
.uri("/api/v1/{categoryId}/reserve-items?keywordType=locationName&keyword=location&page=0&size=3", "education")
.exchange()
.expectStatus().isOk();
ReserveItem saved = reserveItemRepository.save(reserveItem).block();
assertNotNull(saved);
webTestClient.method(HttpMethod.GET)
.uri(API_URL+"?page=0&size=3&isUse=false")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.totalElements").isEqualTo(1)
.jsonPath("$.content[0].reserveItemName").isEqualTo(reserveItem.getReserveItemName());
}
@Test
public void 한건조회_성공() throws Exception {
ReserveItem saved = reserveItemRepository.save(reserveItem).block();
assertNotNull(saved);
ReserveItemResponseDto responseBody = webTestClient.get()
.uri(API_URL+"/{reserveItemId}", saved.getReserveItemId())
.exchange()
.expectStatus().isOk()
.expectBody(ReserveItemResponseDto.class)
.returnResult().getResponseBody();
assertThat(responseBody.getCategoryId()).isEqualTo(category.getCodeId());
assertThat(responseBody.getReserveItemName()).isEqualTo(saved.getReserveItemName());
}
@Test
public void main_예약물품조회_성공() throws Exception {
BDDMockito.when(reserveItemRepository.findCodeDetail(ArgumentMatchers.anyString()))
.thenReturn(Flux.fromIterable(Arrays.asList(Code.builder().codeId("education").codeName("교육").build(),
Code.builder().codeId("equipment").codeName("장비").build(),
Code.builder().codeId("space").codeName("장소").build())));
public void 사용자_포털_메인_예약목록_조회_성공() throws Exception {
ReserveItem saved = reserveItemRepository.save(reserveItem).block();
assertNotNull(saved);
LocalDateTime startDate = LocalDateTime.of(2021, 1, 28, 1,1);
LocalDateTime endDate = LocalDateTime.of(2021, 12, 6, 1,1);
Location location = Location.builder()
.locationId(1L)
.locationName("location")
.sortSeq(1)
.isUse(true)
.build();
ReserveItem reserveItem1 = ReserveItem.builder()
.reserveItemId(1L)
.location(location)
.locationId(location.getLocationId())
.reserveItemName("test")
.categoryId("education")
.categoryName("교육")
.totalQty(100)
.inventoryQty(80)
.operationEndDate(endDate)
.operationStartDate(startDate)
.reserveMethodId("visit")
.isPeriod(false)
.isUse(true)
.build();
ReserveItem reserveItem2 = ReserveItem.builder()
.reserveItemId(1L)
.location(location)
.locationId(location.getLocationId())
.reserveItemName("test")
.categoryId("education")
.categoryName("장비")
.totalQty(100)
.inventoryQty(80)
.operationEndDate(endDate)
.operationStartDate(startDate)
.reserveMethodId("visit")
.isPeriod(false)
.isUse(true)
.build();
ReserveItem reserveItem3 = ReserveItem.builder()
.reserveItemId(1L)
.location(location)
.locationId(location.getLocationId())
.reserveItemName("test")
.categoryId("education")
.categoryName("공간")
.totalQty(100)
.inventoryQty(80)
.operationEndDate(endDate)
.operationStartDate(startDate)
.reserveMethodId("visit")
.isPeriod(false)
.isUse(true)
.build();
reserveItem1.setCreateDate(LocalDateTime.now());
reserveItem2.setCreateDate(LocalDateTime.now());
reserveItem3.setCreateDate(LocalDateTime.now());
BDDMockito.when(reserveItemRepository.findLatestByCategory(ArgumentMatchers.anyInt(), ArgumentMatchers.anyString()))
.thenReturn(Flux.fromIterable(Arrays.asList(reserveItem1, reserveItem2, reserveItem3)));
webTestClient.get()
.uri("/api/v1/reserve-items/latest/3")
Map<String, Collection<ReserveItemMainResponseDto>> responseBody = webTestClient.get()
.uri(API_URL+"/latest/3")
.exchange()
.expectStatus().isOk();
.expectStatus().isOk()
.expectBody(new ParameterizedTypeReference<Map<String, Collection<ReserveItemMainResponseDto>>>() {
})
.returnResult().getResponseBody();
assertThat(responseBody.keySet().size()).isEqualTo(1);
assertThat(responseBody.keySet().contains(category.getCodeId())).isTrue();
Collection<ReserveItemMainResponseDto> reserveItemMainResponseDtos = responseBody.get(category.getCodeId());
reserveItemMainResponseDtos.stream().forEach(reserveItemMainResponseDto -> {
assertThat(reserveItemMainResponseDto.getReserveItemName().equals(saved.getReserveItemName()));
});
}
@Test
public void 한건_등록_성공() throws Exception {
ReserveItemSaveRequestDto requestDto = ReserveItemSaveRequestDto.builder()
.reserveItemName(reserveItem.getReserveItemName())
.categoryId(reserveItem.getCategoryId())
.locationId(reserveItem.getLocationId())
.inventoryQty(reserveItem.getInventoryQty())
.totalQty(reserveItem.getTotalQty())
.operationStartDate(reserveItem.getOperationStartDate())
.operationEndDate(reserveItem.getOperationEndDate())
.reserveMethodId(reserveItem.getReserveMethodId())
.reserveMeansId(reserveItem.getReserveMeansId())
.isUse(reserveItem.getIsUse())
.requestStartDate(reserveItem.getRequestStartDate())
.requestEndDate(reserveItem.getRequestEndDate())
.isPeriod(reserveItem.getIsPeriod())
.selectionMeansId(reserveItem.getSelectionMeansId())
.build();
ReserveItemResponseDto responseBody = webTestClient.post()
.uri(API_URL)
.bodyValue(requestDto)
.exchange()
.expectStatus().isCreated()
.expectBody(ReserveItemResponseDto.class)
.returnResult().getResponseBody();
System.out.println(responseBody);
assertThat(responseBody.getReserveItemName()).isEqualTo(requestDto.getReserveItemName());
}
@Test
public void 한건_수정_성공() throws Exception {
ReserveItem saved = reserveItemRepository.save(reserveItem).block();
assertNotNull(saved);
ReserveItemUpdateRequestDto requestDto = ReserveItemUpdateRequestDto.builder()
.reserveItemName("update")
.categoryId(reserveItem.getCategoryId())
.locationId(reserveItem.getLocationId())
.inventoryQty(reserveItem.getInventoryQty())
.totalQty(reserveItem.getTotalQty())
.operationStartDate(reserveItem.getOperationStartDate())
.operationEndDate(reserveItem.getOperationEndDate())
.reserveMethodId(reserveItem.getReserveMethodId())
.reserveMeansId(reserveItem.getReserveMeansId())
.isUse(reserveItem.getIsUse())
.requestStartDate(reserveItem.getRequestStartDate())
.requestEndDate(reserveItem.getRequestEndDate())
.isPeriod(reserveItem.getIsPeriod())
.selectionMeansId(reserveItem.getSelectionMeansId())
.build();
webTestClient.put()
.uri(API_URL+"/"+saved.getReserveItemId())
.bodyValue(requestDto)
.exchange()
.expectStatus().isNoContent();
ReserveItem findbyid = reserveItemRepository.findById(saved.getReserveItemId()).block();
assertThat(findbyid.getReserveItemName()).isEqualTo("update");
}
@Test
public void 사용여부_false_수정_성공() throws Exception {
ReserveItem saved = reserveItemRepository.save(reserveItem).block();
assertNotNull(saved);
webTestClient.put()
.uri(API_URL+"/"+saved.getReserveItemId()+"/false")
.exchange()
.expectStatus().isNoContent();
ReserveItem findbyid = reserveItemRepository.findById(saved.getReserveItemId()).block();
assertThat(findbyid.getIsUse()).isEqualTo(Boolean.FALSE);
}
@Test
public void 한건_저장_validation_실패() throws Exception {
ReserveItemSaveRequestDto requestDto = ReserveItemSaveRequestDto.builder()
.reserveItemName(reserveItem.getReserveItemName())
.categoryId(reserveItem.getCategoryId())
.locationId(reserveItem.getLocationId())
.inventoryQty(reserveItem.getInventoryQty())
.totalQty(reserveItem.getTotalQty())
.operationStartDate(reserveItem.getOperationStartDate())
.operationEndDate(reserveItem.getOperationEndDate())
.reserveMethodId(reserveItem.getReserveMethodId())
.reserveMeansId(reserveItem.getReserveMeansId())
.isUse(reserveItem.getIsUse())
.isPeriod(reserveItem.getIsPeriod())
.selectionMeansId(reserveItem.getSelectionMeansId())
.build();
ErrorResponse responseBody = webTestClient.post()
.uri(API_URL)
.bodyValue(requestDto)
.exchange()
.expectStatus().isBadRequest()
.expectBody(ErrorResponse.class)
.returnResult().getResponseBody();
assertThat(responseBody.getCode()).isEqualTo(ErrorCode.INVALID_INPUT_VALUE.getCode());
assertThat(responseBody.getErrors().size()).isEqualTo(1);
responseBody.getErrors().stream().forEach(fieldError -> {
assertThat(fieldError.getField()).isEqualTo("requestStartDate");
System.out.println(fieldError.getMessage());
});
}
}

View File

@@ -21,7 +21,7 @@ public class R2dbcConfig{
@Bean
public H2ConnectionFactory connectionFactory() {
return new H2ConnectionFactory(H2ConnectionConfiguration.builder()
.tcp("localhost", "~/querydsl")
.inMemory("testdb")
.property(H2ConnectionOption.DB_CLOSE_DELAY, "-1")
.username("sa")
.build());

View File

@@ -2,20 +2,6 @@ spring:
application:
name: reserve-item-service
datasource:
url: jdbc:h2:mem:testdb;MODE=MYSQL;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false
username: sa
password:
driver-class-name: org.h2.Driver
jpa:
hibernate:
generate-ddl: true
ddl-auto: create-drop
properties:
hibernate:
format_sql: true
default_batch_fetch_size: 1000
show-sql: true
h2:
console:
enabled: true

View File

@@ -1,14 +1,25 @@
CREATE TABLE IF NOT EXISTS location(
location_id BIGINT AUTO_INCREMENT,
location_name VARCHAR(200),
use_at tinyint(1) default 1 null,
sort_seq smallint(3) null,
create_date DATE null,
modified_date DATE null,
created_by VARCHAR(255) null,
last_modified_by VARCHAR(255) null,
CONSTRAINT PERSON_PK PRIMARY KEY (location_id)
);
CREATE TABLE IF NOT EXISTS `code` (
`code_id` varchar(20) NOT NULL COMMENT '코드 id',
`code_name` varchar(500) NOT NULL COMMENT '코드 명',
`parent_code_id` varchar(20) DEFAULT NULL COMMENT '부모 코드 id',
use_at BOOLEAN NULL DEFAULT TRUE COMMENT '사용 여부',
PRIMARY KEY (`code_id`)
) ;
-- location Table Create SQL
CREATE TABLE IF NOT EXISTS location
(
location_id BIGINT NOT NULL AUTO_INCREMENT COMMENT '지역 id',
location_name VARCHAR(200) NULL COMMENT '지역 이름',
sort_seq SMALLINT(3) NULL COMMENT '정렬 순서',
use_at BOOLEAN NULL DEFAULT TRUE COMMENT '사용 여부',
created_by VARCHAR(255) NULL COMMENT '생성자',
create_date DATETIME NULL COMMENT '생성일',
last_modified_by VARCHAR(255) NULL COMMENT '수정자',
modified_date DATETIME NULL COMMENT '수정일',
PRIMARY KEY (location_id)
) ;
-- reserve_item Table Create SQL
@@ -18,20 +29,21 @@ CREATE TABLE IF NOT EXISTS reserve_item
reserve_item_name VARCHAR(200) NULL COMMENT '예약 물품 이름',
location_id BIGINT NULL COMMENT '지역 id',
category_id VARCHAR(20) NULL COMMENT '예약유형 - 공통코드 reserve-category',
capacity_count MEDIUMINT(5) NULL COMMENT '재고/수용인원 수',
total_qty BIGINT(18) NULL COMMENT '재고/수용인원 수',
inventory_qty BIGINT(18) NULL COMMENT '현재 남은 재고/수용인원 수',
operation_start_date DATETIME NULL COMMENT '운영 시작 일',
operation_end_date DATETIME NULL COMMENT '운영 종료 일',
reserve_method_id VARCHAR(20) NULL COMMENT '예약 방법 - 공통코드 reserve-method',
reserve_means_id VARCHAR(20) NULL COMMENT '예약 구분 (인터넷 예약 시) - 공통코드 reserve-means',
request_start_date DATETIME NULL COMMENT '예약 신청 시작 일시',
request_end_date DATETIME NULL COMMENT '예약 신청 종료 일시',
period_at TINYINT(1) NULL DEFAULT 0 COMMENT '기간 지정 가능 여부 - true: 지정 가능, false: 지정 불가',
period_at BOOLEAN NULL DEFAULT FALSE COMMENT '기간 지정 가능 여부 - true: 지정 가능, false: 지정 불가',
period_max_count SMALLINT(3) NULL COMMENT '최대 예약 가능 일 수',
external_url VARCHAR(500) NULL COMMENT '외부링크',
selection_means_id VARCHAR(20) NULL COMMENT '선별 방법 - 공통코드 reserve-selection-means',
free_at TINYINT(1) NULL DEFAULT 1 COMMENT '유/무료 - true: 무료, false: 유료',
paid_at BOOLEAN NULL DEFAULT FALSE COMMENT '유/무료 - false: 무료, true: 유료',
usage_cost DECIMAL(18, 0) NULL COMMENT '이용 요금',
use_at TINYINT(1) NULL DEFAULT 1 COMMENT '사용 여부',
use_at BOOLEAN NULL DEFAULT TRUE COMMENT '사용 여부',
purpose_content VARCHAR(4000) NULL COMMENT '용도',
item_addr VARCHAR(500) NULL COMMENT '주소',
target_id VARCHAR(20) NULL COMMENT '이용 대상 - 공통코드 reserve-target',
@@ -45,5 +57,10 @@ CREATE TABLE IF NOT EXISTS reserve_item
created_by VARCHAR(255) NULL COMMENT '생성자',
modified_date DATETIME NULL COMMENT '수정일',
last_modified_by VARCHAR(255) NULL COMMENT '수정자',
PRIMARY KEY (reserve_item_id)
);
PRIMARY KEY (reserve_item_id),
CONSTRAINT FK_reserve_item_location_id FOREIGN KEY (location_id)
REFERENCES location (location_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ;