반응형

* 이동욱 저자의 스프링 부트와 AWS로 혼자 구현하는 웹서비스 교재 참고

 

1. 개요

 - 롬복 설치 및 롬복을 사용하여 Dto 객체를 생성한다.

 - 테스트용 controller를 생성한다.

 - Junit을 통해 테스트한다.

 

2. 롬복 설치 및 이클립스 연동

 2.1. 롬복 설치 (gradle)

org.projectlombok:lombok 추가

  - gradle에 롬복 의존성을 추가하여 라이브러리를 다운받는다.

 

 2.2. 롬복 실행

  - 라이브러리가 다운받아졌으면 롬복이 설치된 경로(gradle Home)로 이동한다.

  - 그 후 관리자 권한으로 cmd를 실행한 후 jar파일을 실행한다.

롬복 설치 경로

 2.3. STS 연동

  - 롬복 install 창이 뜨면 Specify location 을 선택하여 STS 실행파일을 선택 후 install /Update 를 클릭한다.

   * 여기서 access 에러가 뜬다면 cmd를 관리자 권한으로 실행하면 된다.

롬복 연동

 2.4. STS 연동 완료

  - 다음과 같은 창이 출력되면 설치 및 연동이 완료된 것이다.

  - STS 및 이클립스를 실행중이라면 재시작 시 적용된다.

연동 완료

3. HelloController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ssk.springboot.web;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.ssk.springboot.web.dto.HelloResponseDto;
 
@RestController
public class HelloController {
 
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
    
    @GetMapping("/hello/dto")
    public HelloResponseDto helloDto(@RequestParam("name"String name, @RequestParam("amount"int amount){
        return new HelloResponseDto(name,amount);
    }
}
 
 
cs

 - @RestController : Json을 반환하는 컨트롤러로 만든다. @ResponseBody를 메서드마다 선언했던 것과 동일하다.

 - @GetMapping : Get 방식을 지원한다.

 - @RequestParam : request 파라미터를 가져온다.

 

4. HelloResponseDto.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.ssk.springboot.web.dto;
 
import lombok.Getter;
import lombok.RequiredArgsConstructor;
 
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {
 
    private final String name;
    private final int amount;
}
 
cs

 - @Getter : 선언된 필드에 대해 Getter를 자동 생성한다.

 - @RequiredArgsConstructor : final로 선언된 필드가 포함된 생성자를 생성한다.

   > HelloResponseDto(String name, String amount) 라는 생성자가 내부적으로 생성된 것이다.

 

5. HelloControllerTest 클래스 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@RunWith(SpringRunner.class//스프링 실행자를 JUnit 내에 저장된 실행자와 함께 실행
@WebMvcTest(controllers = HelloController.class// Mvc Test에 사용하는 어노테이션, 테스트 컨트롤러 리스트에 HelloController를 추가
public class HelloControllerTest {
    
    @Autowired
    private MockMvc mvc; //mvc 테스트용 객체
    
    @Test
    public void hello가_리턴된다() throws Exception{
        String hello = "hello";
        mvc.perform(get("/hello")) //hello로 get 통신
            .andExpect(status().isOk()) //200인지 검사
            .andExpect(content().string(hello)); //response 값이 hello 인지 검사
        
    }
    
    @Test
    public void helloDto가_리턴된다() throws Exception{
        String name = "hello";
        int amount = 1000;
        
        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)));
    }
}
cs

 - @RunWith(SpringRunner.class) : 스프링 테스트에 필요한 스프링 실행자인 SpringRunner를 실행시킨다.

 - @WebMvcTest(controllers = HelloController.class) : 스프링 MVC 테스트에 사용하는 어노테이션이다. 테스트 controller로 HelloController를 지정했다.

 - mvc.perform(get("/hello")) : hello로 get요청을 보낸다. perform 메서드는 메서드 체이닝이 지원되며 andExpect 같은 검증 메서드와 함께 사용한다.

 - param("name",name) : 요청 파라미터 값을 추가한다. 단 String 형태만 허용되기 때문에 amount 값을 변환했다.

 - jsonPath : Json 응답값을 필드별로 검증할 수 있는 메서드이다. $를 기준으로 필드명을 명시한다. 

 

6. Junit 실행을 통한 테스트

Junit 실행

 - @Test 어노테이션이 붙은 메서드의 테스트가 정상적으로 실행됨을 확인할 수 있다.

 

 

반응형

+ Recent posts