학습노트2 - 첫 예제, 테스트 코드

TDD

  • 테스트가 주도 하는 개발
  • 레드 그린 사이클

항상 실패하는 테스트를 먼저 작성 RED
테스트 통과하는 프로덕션 코드 작성 GREEN
테스트 통과 하면 프로덕션 코드를 리팩토링 REFACTOR

https://repo.yona.io/doortts/blog/issue/1

단위 테스트 (Unit Test)

  • TDD 가 이야기 하는 첫번째 단계인 기능 단위의 테스트 코드 작성

  • 단위 테스트 없이 할때의 개발/테스트/디버깅 Flow

  1. 코드 작성
  2. 프로그램 (Tomcat) 실행
  3. Postman 으로 API 테스트, HTTP 요청 보내기
  4. 요청결과를 System.out.println 으로 찍은 메세지로 눈으로 검증
  5. 결과가 다르면 프로그램(Tomcat) 주지 하고 코드를 수정

xUnit

가장 대중적인 테스트 프레임워크
자바는 JUnit, 2000년도에 JUnit4 -> JUnit5 로 넘어간 것으로 보임

Controller 예제 & Test Code

  1. @GetRestController
  2. @GetMapping
  3. @RequestParam
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@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);
}
}

Test Code

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)
@WebMvcTest
public class HelloControllerTest {

@Autowired
private MockMvc mvc;

@Test
public void hello가_리턴된다() throws Exception {
String hello = "hello";

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

@Test
public void hellodto가_리턴된다() throws Exception {
String name = "name";
int amount = 100;

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)));
}
}

Lombok 예제 & Test Code

  1. DTO 작성, @Getter, @RequiredArgsConstructor, 변수는 private final
  2. Assertj 사용
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
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {

private final String name;
private final int amount;

}

public class HelloResponseDtoTest {

@Test
public void 롬복_기능_테스트() {
//given
String name = "test;";
int amount = 1000;

//when
HelloResponseDto dto = new HelloResponseDto(name, amount);

//then
assertThat(dto.getName()).isEqualTo(name);
assertThat(dto.getAmount()).isEqualTo(amount);
}
}