스프링 부트 프로젝트(레스토랑 예약 사이트 만들기)-가게상세-1 08강 해석

Psj·2021년 12월 19일
0

#1 id값에 따른 가게상세 반환(방법1)

/test/~/interfaces/RestaurantControllerTest.java

package kr.co.fastcampus.eatgo.interfaces;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.core.StringContains.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class) // api 요청처리 테스트를 해주기위한 스프링자체의 어노테이션
@WebMvcTest(RestaurantController.class) // 특정 컨트롤러를 테스트해준다는것을 명시하는 어노테이션
public class RestaurantControllerTest {

    @Autowired
    private MockMvc mvc; // MockMvc생성

    @Test
    public void list() throws Exception {  // perform 메서드가 가진 try-catch 에외처리를 이 메서드내에서 해줘야하는데 여기서 처리안하고 다음에 받을 클래스로 예외를 넘기고싶을때 throw 사용
        mvc.perform(get("/restaurants")) // "/restaurant" 에 get 요청을 한다는것
        .andExpect(status().isOk()) // "/restaurant" 에 get 요청을 한다는것에대한 status가, OK가 떠야된다는것
        .andExpect(content().string(containsString("\"id\":1004"))) // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)
        .andExpect(content().string(containsString("\"name\":\"Bob zip\""))); // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)

    }

    @Test
    public void detail() throws Exception {
        mvc.perform(get("/restaurants/1004")) // id값 1004 요청시 데이터가 잘 반환되는지 테스트
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("\"id\":1004")))
                .andExpect(content().string(containsString("\"name\":\"Bob zip\"")));

        mvc.perform(get("/restaurants/2020"))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("\"id\":2020")))
                .andExpect(content().string(containsString("\"name\":\"Cyber Food\"")));
    }
}

/main/~/interfaces/RestaurantController.java

package kr.co.fastcampus.eatgo.interfaces;

import kr.co.fastcampus.eatgo.domain.Restaurant;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class RestaurantController {

    @GetMapping("/restaurants")
    public List<Restaurant> list(){
        List<Restaurant> restaurants = new ArrayList<>(); // 리스트 객체생성

        Restaurant restaurant = new Restaurant(1004L,"Bob zip", "Seoul"); // 이름과 주소를 가진 객체 생성
        restaurants.add(restaurant); // restaurants 리스트객체에 위에서 생성한 restaurant객체를 넣은것이다.

        return restaurants;
    }

    @GetMapping("/restaurants/{id}") // {id} 이런식으로 사용해 특정한 id를 유동적으로 받을수있게한다
    public Restaurant detail(@PathVariable("id") Long id){ // {id}와 @PathVariable("id") 가 일치해야한다

        Restaurant restaurant = null; // 디폴트값으로 null을 처리하는것은 아래의 if문 둘다 해당되지 않을경우를 지정해야해서이다.

        if(id == 1004) {
            restaurant =new Restaurant(1004L, "Bob zip", "Seoul");
        }
        if(id == 2020){
            restaurant =new Restaurant(2020L, "Cyber Food", "Seoul");
        }
        return restaurant;
    }

}

위처럼 요청이 들어오는 id값에 따라 if문을 만들어서 객체를 생성해야한다면
위 예제에서는 두개만 만들면되지만 우리는 우리가 등록해야하는 모든가게의 수만큼 if문을 작성해야되기때문에

위 방법은 상당히 비효율적이라고 할 수 있다.

#2 id값에 따른 가게상세 반환(방법2)

/test/~/interfaces/RestaurantControllerTest.java

package kr.co.fastcampus.eatgo.interfaces;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import static org.hamcrest.core.StringContains.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class) // api 요청처리 테스트를 해주기위한 스프링자체의 어노테이션
@WebMvcTest(RestaurantController.class) // 특정 컨트롤러를 테스트해준다는것을 명시하는 어노테이션
public class RestaurantControllerTest {

    @Autowired
    private MockMvc mvc; // MockMvc생성

    @Test
    public void list() throws Exception {  // perform 메서드가 가진 try-catch 에외처리를 이 메서드내에서 해줘야하는데 여기서 처리안하고 다음에 받을 클래스로 예외를 넘기고싶을때 throw 사용
        mvc.perform(get("/restaurants")) // "/restaurant" 에 get 요청을 한다는것
        .andExpect(status().isOk()) // "/restaurant" 에 get 요청을 한다는것에대한 status가, OK가 떠야된다는것
        .andExpect(content().string(containsString("\"id\":1004"))) // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)
        .andExpect(content().string(containsString("\"name\":\"Bob zip\""))); // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)

    }

    @Test
    public void detail() throws Exception {
        mvc.perform(get("/restaurants/1004")) // id값 1004 요청시 데이터가 잘 반환되는지 테스트
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("\"id\":1004")))
                .andExpect(content().string(containsString("\"name\":\"Bob zip\"")));

        mvc.perform(get("/restaurants/2020"))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("\"id\":2020")))
                .andExpect(content().string(containsString("\"name\":\"Cyber Food\"")));
    }
}

/main/~/interfaces/RestaurantController.java

package kr.co.fastcampus.eatgo.interfaces;

import kr.co.fastcampus.eatgo.domain.Restaurant;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class RestaurantController {

    @GetMapping("/restaurants")
    public List<Restaurant> list(){
        List<Restaurant> restaurants = new ArrayList<>(); // 리스트 객체생성

        Restaurant restaurant = new Restaurant(1004L,"Bob zip", "Seoul"); // 이름과 주소를 가진 객체 생성
        restaurants.add(restaurant); // restaurants 리스트객체에 위에서 생성한 restaurant객체를 넣은것이다.

        return restaurants;
    }

    @GetMapping("/restaurants/{id}") // {id} 이런식으로 사용해 특정한 id를 유동적으로 받을수있게한다
    public Restaurant detail(@PathVariable("id") Long id){ // {id}와 @PathVariable("id") 가 일치해야한다

        List<Restaurant> restaurants = new ArrayList<>(); // 각각의 restaurant를 담을 리스트를 생성

        restaurants.add(new Restaurant(1004L, "Bob zip", "Seoul"));
        restaurants.add(new Restaurant(2020L, "Cyber Food", "Seoul"));

        Restaurant restaurant = restaurants.stream() // java의 stream사용
                .filter(r -> r.getId().equals(id)) // 리스트에 들어있는 restaurant의 id중 요청들어오는 id와 같은것이 있어야하고
                .findFirst() // 그중 첫번째값을 골라(id는 유니크한 값이기때문에 어차피 하나밖에 없을것이다)
                .get(); // 가져오라는것이다.
                // .get(); 을 지우고 orElse(null); 을 넣어도 정상작동하는데 이것은 요청들어오는값과 일치하는 값이 없을때 표시할값을 orElse()안에 적는것이다 여기서는 null을 적었으니 일치하는값으없을때 null이 반환될것이다.

        return restaurant;
    }

}

리스트에 각 객체를 넣고 요청과 일치하는 id값에따라 리스트에서 불러오는식으로 변경하였다.

profile
Software Developer

0개의 댓글