[Spring Boot] Test Code

inยท2023๋…„ 9์›” 11์ผ
0

Spring

๋ชฉ๋ก ๋ณด๊ธฐ
4/7

๐Ÿ“Œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด์•ผ ํ•˜๋Š” ์ด์œ 

  • ๊ฐœ๋ฐœ๋‹จ๊ณ„ ์ดˆ๊ธฐ์— ๋ฌธ์ œ๋ฅผ ๋ฐœ๊ฒฌํ•  ์ˆ˜ ์žˆ์Œ
  • ์ฝ”๋“œ๋ฅผ ๋ฆฌํŒฉํ† ๋งํ•˜๊ฑฐ๋‚˜ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์—…๊ทธ๋ ˆ์ด๋“œ ์‹œ ๊ธฐ์กด ๊ธฐ๋Šฅ์ด ์ž˜ ์ž‘๋™ํ•˜๋Š”์ง€ ํ™•์ธ ๊ฐ€๋Šฅ
  • ๊ธฐ๋Šฅ์— ๋Œ€ํ•œ ๋ถˆํ™•์‹ค์„ฑ ๊ฐ์†Œ

โœ”๏ธ TDD
ํ…Œ์ŠคํŠธ ์ฃผ๋„ ๊ฐœ๋ฐœ(Test Driven Development)

๐Ÿ“Œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ ์˜ˆ์ œ

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

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = HomeController.class)
public class HomeControllerTest {

   @Autowired
   private MockMvc mvc;

   @Test
   public void home_return() throws Exception {
       //when
       String home = "home";

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

โœ”๏ธ @RunWith(SpringRunner.class)
ํ…Œ์ŠคํŠธ๋ฅผ ์ง„ํ–‰ํ•  ๋•Œ JUnit์— ๋‚ด์žฅ๋œ ์‹คํ–‰์ž ์™ธ์— ๋‹ค๋ฅธ ์‹คํ–‰์ž ์‹คํ–‰
์Šคํ”„๋ง ๋ถ€ํŠธ ํ…Œ์ŠคํŠธ์™€ JUnit ์‚ฌ์ด์˜ ์—ฐ๊ฒฐ์ž ์—ญํ• 

โœ”๏ธ @WebMvcTest
Web(Spring MVC)์— ์ง‘์ค‘ํ•  ์ˆ˜ ์žˆ๋Š” ์–ด๋…ธํ…Œ์ด์…˜
@Controller, @ControllerAdvice ๋“ฑ ์‚ฌ์šฉ๊ฐ€๋Šฅ
@Service, @Compnent, @Repository ์‚ฌ์šฉ๋ถˆ๊ฐ€

โœ”๏ธ @AutoWired
์Šคํ”„๋ง์ด ๊ด€๋ฆฌํ•˜๋Š” Bean ์ฃผ์ž…์‹œ์ผœ์คŒ

โœ”๏ธ MockMvc
์›น API ํ…Œ์ŠคํŠธํ•  ๋•Œ ์‚ฌ์šฉ
์ด๋ฅผ ํ†ตํ•ด HTTP GET, POST, DELETE ๋“ฑ์— ๋Œ€ํ•œ API ํ…Œ์ŠคํŠธ ๊ฐ€๋Šฅ

โœ”๏ธ mvc.perform(get("/home"))
/home ์ฃผ์†Œ๋กœ HTTP GET ์š”์ฒญ

โœ”๏ธ .andExpect(status().isOK())
๊ฒฐ๊ณผ๋ฅผ ๊ฒ€์ฆํ•˜๋Š” andExpect๋กœ ์—ฌ๋Ÿฌ๊ฐœ ๋ถ™์—ฌ์„œ ์‚ฌ์šฉ ๊ฐ€๋Šฅ
status()๋Š” HTTP Header๋ฅผ ๊ฒ€์ฆํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๊ฒฐ๊ณผ์— ๋Œ€ํ•œ HTTP Status ์ƒํƒœ ํ™•์ธ ๊ฐ€๋Šฅ
isOK()๋Š” 200 ์ฝ”๋“œ๊ฐ€ ๋งž๋Š”์ง€ ํ™•์ธํ•˜๊ณ  ์žˆ์Œ

โœ”๏ธ .andExpect(content().string(hello))
mvc.perform์˜ ๊ฒฐ๊ณผ ๊ฒ€์ฆ
์‘๋‹ต ๋ณธ๋ฌธ์˜ ๋‚ด์šฉ ๊ฒ€์ฆ


[์ฐธ๊ณ  ์ž๋ฃŒ]

๐Ÿ”—๋งํฌ
๐Ÿ”—๋งํฌ

0๊ฐœ์˜ ๋Œ“๊ธ€