Skip to content

Commit

Permalink
refactor from return ResponseEntity<Object> to Object and Add @Respon…
Browse files Browse the repository at this point in the history
…seStatus
  • Loading branch information
ce-pong committed Feb 26, 2024
1 parent db89abc commit 8567b83
Show file tree
Hide file tree
Showing 9 changed files with 147 additions and 35 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,41 +6,39 @@
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.time.LocalDateTime;
import java.util.stream.Collectors;


@ControllerAdvice
@RestControllerAdvice
public class ControllerExceptionHandler {

@ExceptionHandler(value = {InternalServerException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Object> handleInternalServerException(InternalServerException internalServerException, WebRequest request) {
ApiErrorResponse response = new ApiErrorResponse(
public ApiErrorResponse handleInternalServerException(InternalServerException internalServerException, WebRequest request) {

return new ApiErrorResponse(
LocalDateTime.now(),
HttpStatus.INTERNAL_SERVER_ERROR.value(),
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),
internalServerException.getMessage(),
request.getDescription(false)
);

return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(value = {MethodArgumentNotValidException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException exception, WebRequest request) {
public ApiErrorResponse handleValidationExceptions(MethodArgumentNotValidException exception, WebRequest request) {

ApiErrorResponse response = new ApiErrorResponse(
return new ApiErrorResponse(
LocalDateTime.now(),
HttpStatus.BAD_REQUEST.value(),
HttpStatus.BAD_REQUEST.getReasonPhrase(),
"Validation error",
request.getDescription(false)
);

return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.kbtg.bootcamp.posttest.exception;

public class NotFoundException extends RuntimeException{
public NotFoundException(String message){
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,22 @@ public LotteryController(LotteryService lotteryService){
}

@GetMapping(value = "/lotteries")
public ResponseEntity<LotteryListResponse> getAvailableLottery(){
@ResponseStatus(value = HttpStatus.OK)
public LotteryListResponse getAvailableLottery(){

LotteryListResponse result = lotteryService.getAvailableTicketIds();

return ResponseEntity.ok(result);
return lotteryService.getAvailableTicketIds();
}

@PostMapping(value = "/admin/lotteries")
public ResponseEntity<LotteryResponse> createLottery(@RequestBody
@Validated
LotteryDto request){

LotteryResponse result = lotteryService.createLottery(request);
@ResponseStatus(HttpStatus.CREATED)
public LotteryResponse createLottery(@RequestBody @Validated LotteryDto request){

return new ResponseEntity<>(result, HttpStatus.CREATED);
return lotteryService.createLottery(request);
}

@PostMapping(value = "/users/{userId}/lotteries/{ticketId}")
public ResponseEntity<LotteryPurchaseReponse> purchaseTicket(
@ResponseStatus(HttpStatus.CREATED)
public LotteryPurchaseReponse purchaseTicket(
@PathVariable(value = "userId") @TenDigitUser String userId,
@PathVariable(value = "ticketId") @SixDigitTicket String ticketId){

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,29 @@

import com.kbtg.bootcamp.posttest.exception.InternalServerException;

import com.kbtg.bootcamp.posttest.user.User;
import com.kbtg.bootcamp.posttest.user.UserRepository;
import com.kbtg.bootcamp.posttest.user.UserTicketRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


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

@Service
public class LotteryService {
private final LotteryRepository lotteryRepository;

public LotteryService(LotteryRepository lotteryRepository){
private final UserTicketRepository userTicketRepository;

private final UserRepository userRepository;

public LotteryService(LotteryRepository lotteryRepository, UserTicketRepository userTicketRepository, UserRepository userRepository) {
this.lotteryRepository = lotteryRepository;
this.userTicketRepository = userTicketRepository;
this.userRepository = userRepository;
}

public Boolean checkValidTicket(String ticket){
Expand Down Expand Up @@ -49,4 +60,9 @@ public LotteryResponse createLottery(LotteryDto request){

}

@Transactional
public LotteryPurchaseReponse purchaseLottery(String userId,String ticketId){

return null;
}
}
23 changes: 23 additions & 0 deletions posttest/src/main/java/com/kbtg/bootcamp/posttest/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,27 @@ public class User {

@OneToMany(mappedBy = "user")
private List<UserTicket> tickets;

public User() {
}

public User(String userId) {
this.userId = userId;
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public List<UserTicket> getTickets() {
return tickets;
}

public void setTickets(List<UserTicket> tickets) {
this.tickets = tickets;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.kbtg.bootcamp.posttest.user;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends JpaRepository<User,String> {
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,28 @@ public class UserTicket {
@ManyToOne
@JoinColumn(name = "user_id")
private User user;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Lottery getLottery() {
return lottery;
}

public void setLottery(Lottery lottery) {
this.lottery = lottery;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.kbtg.bootcamp.posttest.user;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserTicketRepository extends JpaRepository<UserTicket,Integer> {
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package com.kbtg.bootcamp.posttest.lottery;

import com.kbtg.bootcamp.posttest.exception.InternalServerException;
import org.junit.jupiter.api.BeforeEach;
import com.kbtg.bootcamp.posttest.user.User;
import com.kbtg.bootcamp.posttest.user.UserRepository;
import com.kbtg.bootcamp.posttest.user.UserTicket;
import com.kbtg.bootcamp.posttest.user.UserTicketRepository;

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.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;

import org.springframework.boot.test.context.SpringBootTest;


import java.util.Collections;
import java.util.List;
Expand All @@ -18,21 +22,24 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@SpringBootTest
class LotteryServiceTest {

@Mock
private LotteryRepository lotteryRepository;

private LotteryService lotteryService;
@Mock
private UserTicketRepository userTicketRepository;

@BeforeEach
void setUp() {
lotteryRepository = Mockito.mock(LotteryRepository.class);
lotteryService = new LotteryService(lotteryRepository);
}
@Mock
private UserRepository userRepository;

@InjectMocks
private LotteryService lotteryService;

@Test
@DisplayName("Get Available Ticket IDs With No Data Should Return Empty List Response")
void getAvailableTicketIds_withNoData_ShouldReturnResponseWithEmptyList() {
void whenGetAvailableTicket_withNoData_ShouldReturnResponseWithEmptyList() {
// Arrange
when(lotteryRepository.findByAmountMoreThanZero()).thenReturn(Collections.emptyList());

Expand All @@ -46,7 +53,7 @@ void getAvailableTicketIds_withNoData_ShouldReturnResponseWithEmptyList() {

@Test
@DisplayName("Get Available Ticket IDs With Data Should Return Correctly List Of Ticket Id")
void getAvailableTicketIds_withNoData_ShouldReturnResponseWithListStringTicketId() {
void gwhenGetAvailableTicket_withData_ShouldReturnResponseWithListStringTicketId() {
// Arrange
Lottery lottery1 = new Lottery();
lottery1.setTicketId("000001");
Expand Down Expand Up @@ -83,7 +90,7 @@ void whenRetrievingTicketsFails_ShouldThrowInternalServerException() {

@Test
@DisplayName("Add lottery should return lottery response")
void whenAddLottery_ShouldReturnLotteryResponseWithTicket(){
void whenCreateLottery_ShouldReturnLotteryResponseWithTicket(){
// Arrange
LotteryDto request = new LotteryDto("000001",80,1);
Lottery lottery = new Lottery("000001",80,1);
Expand All @@ -106,4 +113,28 @@ void whenCreateLotteryFails_ShouldThrowInternalServerException() {
// Act & Assert
assertThrows(InternalServerException.class, () -> {lotteryService.createLottery(request);});
}

@Test
@DisplayName("Purchase lottery should be return id from User_ticket")
void whenPurchaseLottery_ShouldReturnLotteryPurchaseResponseWithUserTicketId(){

// Arrange
String userId = "0123456789";
User user = new User(userId);
String ticket = "000001";
Lottery lottery = new Lottery(ticket,80,1);
UserTicket userTicket = new UserTicket();
userTicket.setId(1);
userTicket.setUser(user);
userTicket.setLottery(lottery);

when(userTicketRepository.save(any(UserTicket.class))).thenReturn(userTicket);

// Act
LotteryPurchaseReponse actual = lotteryService.purchaseLottery(userId,ticket);

// Assert
int expected = 1;
assertEquals(expected,actual.id());
}
}

0 comments on commit 8567b83

Please sign in to comment.