# 테스트 코드 작성
더보기
package com.thuthi.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
더보기
package com.thuthi.springboot.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
}
더보기
package com.thuthi.springboot.web;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
@ExtendWith(SpringExtension.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));
}
}
# Junit5로 변경
책에서는 Junit4로 진행하는데, Junit5로 변경하여 진행했다.
가장 큰 차이점은,
@RunWith(SpringRunner.class) $\rightarrow$ @ExtendWith(SpringExcetion.class)
import org.junit.test $\rightarrow$ import org.junit.jupiter.api.Test
이렇게 2개다.
# Lombok 설치 및 변경
더보기
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
implementation 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
lombok 패키지를 추가해주고, lombok 플러그인을 설치해야하는데, 이미 설치 되어 있으므로 생략.
# Lombok으로 DTO 만들기
더보기
package com.thuthi.springboot.web.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public class HelloResponseDto {
private final String name;
private final int amount;
}
더보기
package com.thuthi.springboot.web.dto;
import static org.assertj.core.api.Assertions.*;
import org.junit.jupiter.api.Test;
class HelloResponseDtoTest {
@Test
public void 롬복_기능_테스트() throws Exception {
// 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);
}
}