실습/AWS

6. 스프링부트와 AWS - 롬복 활용하기 2

ksge7 2021. 4. 28. 02:18

테스트가 마무리됐다면 이제 기존에 만든 HelloController를 수정하도록 하자.

 

이전에 만든 HelloResponseDto를 HelloController에 적용할 예정이다.

1. HelloController에 코드 추가하기

 

기존 코드를 위와 같이 코드를 추가해준다.

 

@RequestParam:

외부에서 API로 넘긴 파라미터를 가져오는 어노테이션.

외부에서 name이란 이름으로 파라미터를 넘기면 이는 name(string name)에 저장된다.

 

좀 더 간단히 설명하면 파라미터를 통해 넘어온 자료를 Dto 객체를 생성할 때 저장하게 해주는 코드다.

2. HelloControllerTest 수정하기

이제 위와 같이 controller의 코드를 수정했으므로 이를 테스트할 코드를 추가해보자.

 

 

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.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HelloController.class)
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void hello_test() throws Exception{
        String hello = "hello";

        mvc.perform(get("/hello"))
                .andExpect(status().isOk())
                .andExpect(content().string(hello));
    }

    @Test
    public void helloDto_Test() throws Exception{

        String name = "학생";
        int amount = 999;

        mvc.perform(
                get("/hello/dto")
                        .param("name", name)
                        .param("amount", String.valueOf(amount)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name", is(name)))
                .andExpect(jsonPath("$.amount", is(amount)));
    }

}

 

위와 같이 코드를 추가하면 된다.

 

코드가 길어서 복잡해보이지만 분해해서 보면 그리 어렵진 않다.

 

우선 첫번째 hello_test() 메서드는 이전에 적은 내용이므로 넘어가고

 

helloDto_Test() 메서드를 보도록 하자.

 

- get("hello/dto"): get요청을 시도한다.

- .param("name", name): name을 파라미터로 전달한다.

- .param("amount", String.valueOf(amount): amount를 스트링으로 바꿔서 전달한다.

- jsonPath("$.name is (name)): json으로 응답되는 값을 멤버 변수 별로 검증하는 메서드

- jsonPath("$.amount is (amount)): json으로 응답되는 값을 멤버 변수 별로 검증하는 메서드

 

간단히 이야기하면 hello_test메서드와 마찬가지다.

 

멤버 변수를 선언하고 해당 멤버 변수를 파라미터로 전달하면서 get요청을 한다.

 

그리고 요청과 함께 전달된 파라미터값이 제대로 전달됐는지 확인하는 과정이다.

 

 

코드 입력만 잘 했다면 위와 같은 성공 메시지를 볼 수 있다.