스프링 부트 프로젝트(레스토랑 예약 사이트 만들기)-가게목록 07강 해석

Psj·2021년 12월 15일
0

#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 {  // mvc.perform에서 perform에서 예외가 뜰수있기때문에 throws Exception을 붙인다.
                                           // perform 메서드가 가진 try-catch 에외처리를 이 메서드내에서 해줘야하는데 여기서 처리안하고 다음에 받을 클래스로 예외를 넘기고싶을때 throw 사용
        mvc.perform(get("/restaurants")) // "/restaurant" 에 get 요청을 한다는것
        .andExpect(status().isOk()) // "/restaurant" 에 get 요청을 한다는것에대한 status가, OK가 떠야된다는것
        //.andExpect(content().string(containsString("Bob zip"))); // 이렇게도 테스트할수있지만 content()에 반환되는 모든값중에서, "Bob zip" 이라는 String만 가지고있으면 통과한다는 테스트로 불명확한테스트이다.
        .andExpect(content().string(containsString("\"name\":\"Bob zip\""))) // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)
        .andExpect(content().string(containsString("\"address\":\"Seoul\""))) // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)
        .andExpect(content().string(containsString("\"id\":1004"))); // 이렇게 JSON 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. ( 현재 id를 넣는 생성자를 만들지 않았으니 통과되지않는다.)
    }

}

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.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("Bob zip", "Seoul"); // 이름과 주소를 가진 객체 생성
        restaurants.add(restaurant); // restaurants 가게목록 객체에 위에서 생성한 restaurant 가게하나의 객체를 넣은것이다.

        return restaurants;
    }

}

#2 id를 가진 가게로 수정하여 가게목록에 추가

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 {  // mvc.perform에서 perform에서 예외가 뜰수있기때문에 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 형태로 테스트를해야 어디에 어떤값이 반환되는지 정확한 테스트를 할수가 있다. (통과)


    }

}

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.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"); // id와 이름과 주소를 가진 객체 생성
        restaurants.add(restaurant); // restaurants 리스트객체에 위에서 생성한 restaurant객체를 넣은것이다.

        return restaurants;
    }

}

test/~/domain/RestaurantTests.java

package kr.co.fastcampus.eatgo.domain;

import org.junit.Test;

import static org.hamcrest.core.Is.is; // assertThat()에서 is 사용시 이것사용
import static org.junit.Assert.*;

public class RestaurantTests {

    @Test // 테스트코드 작성시 사용하는 어노테이션
    public void creation(){ // Restaurant 객체 생성 테스트

        Restaurant restaurant = new Restaurant(1004L,"Bob zip", "Seoul"); // Restaurant 객체 생성

        assertThat(restaurant.getId(),is(1004L)); // id 확인
        assertThat(restaurant.getName(), is("Bob zip")); //이름 확인
        assertThat(restaurant.getAddress(), is("Seoul")); //주소 확인
        
        // assertThat은 어떤것은 어떤것이어야된다는 가정문이다.
        // is()를 사용하면 왼쪽의 restaurant.getName() 값이 is("Bob zip")와 같아야 한다는 것이다.


    }

    public void information(){ // Restaurant 정보 테스트
        Restaurant restaurant = new Restaurant(1004L,"Bob zip", "Seoul"); // id와 이름과 주소를 생성자에 넣어 객체생성

        assertThat(restaurant.getInformaion(), is("Bob zip in Seoul")); //정보 확인
    }
}

main/~/domain/Restaurant.java

package kr.co.fastcampus.eatgo.domain;

public class Restaurant {

    private final Long id;
    private final String name;
    private final String address;


    public Restaurant(Long id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    public Long getId() {
        return id;
    }

    public String getName() { // 생성된 객체의 이름 반환
        return name;
    }

    public String getAddress() { // 생성된 객체의 주소 반환
        return address;
    }

    public String getInformaion() { // 생성된 객체의 정보 반환
        return name + " in " + address;
    }
}
profile
Software Developer

0개의 댓글