MockMvc
MockMvc๋ฅผ ์ด์ฉํ ๊ฐ๋จํ ํ ์คํธ ์ฝ๋๋ฅผ ๋ง๋ค์ด๋ณด์.
Controller
package com.vividswan.spring.web;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PracticeController {
@GetMapping("/practice")
public String practice(){
return "hello world!";
}
}
/practice
๋ก get ์์ฒญ์ ํ์์ ๋,hello world!
๋ฅผ ๋์ฐ๊ฒ ํด์ฃผ๋ ๊ฐ๋จํ ์ปจํธ๋กค๋ฌ๋ฅผ ๋ง๋ ๋ค.
@RestController๋ ๊ฐ์ฒด๋ฅผ return ํ๋ฉด JSON ๋ฐ์ดํฐ ํ์์ผ๋ก ๋ฐํํด ์ฃผ๋ ์ปจํธ๋กค๋ฌ์ด๋ค.
์ฌ๊ธฐ์ ๊ฐ๋จํ๊ฒ "hello world"๋ผ๋ String ์๋ฃ๋ฅผ ํ๋ฉด์ ๋์์ค๋ค.
Test Code
package com.vividswan.spring.web;
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.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@WebMvcTest(controllers=PracticeController.class)
public class PracticeControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void practice_ํ
์คํธ() throws Exception{
String data = "hello world!";
mvc.perform(get("/practice"))
.andExpect(status().isOk())
.andExpect(content().string(data));
}
}
@Autowired
private MockMvc mvc;
Autowired
๋ก MockMvc
๋ฅผ mvc
๋ผ๋ ๋ณ์์ ์์กด์ฑ ์ฃผ์
ํ๋ค.
@Test
public void practice_ํ
์คํธ() throws Exception{
String data = "hello world!";
mvc.perform(get("/practice"))
.andExpect(status().isOk())
.andExpect(content().string(data));
}
@Test
test๋ฅผ ์ํ ๋ฉ์๋์๋ ํญ์ @Test ์ด๋
ธํ
์ด์
์ ๋ถ์ฌ์ค๋ค.
"hello world"๋ผ๋ data String๊ณผ /practice
๋ก get ์์ฒญ๋์ ๋ ์๋ตํ ๋ด์ฉ์ด ๊ฐ์์ง ํ์ธํ๋ ๊ณผ์ ์ด๋ค.
mvc.perform(get("/practice"))
MockMvc๋ฅผ ์ด์ฉํด /practice
๋ก get ์์ฒญ์ ๋ณด๋ธ ์ํฉ์ ๋ง๋ ๋ค.
andExpect(status().isOk())
์ฐ๊ฒฐ ์ํ๊ฐ OK(200๋ฒ๋
)์ธ์ง ํ์ธํ๋ค.
andExpect(content().string(data));
์๋ตํ ๋ด์ฉ์ด data์ ๊ฐ๊ณผ ๊ฐ์์ง ํ์ธํ๋ค.
Test ๊ฒฐ๊ณผ ํ์ธ
ํ
์คํธ๋ฅผ ๋๋ ค๋ณด๊ณ ์ฑ๊ณตํ๋ฉด ์์ ๊ฐ์ ์ด๋ก ๋ฒํผ๊ณผ ๋ฉ์์ง๊ฐ ์ถ๋ ฅ๋๋ค.
ํ
์คํธ์ ์คํจํ๋ฉด ๋นจ๊ฐ ๋ฒํผ์ด ๋์จ๋ค.
'Spring' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Inversion of Control (์ ์ด์ ์ญ์ ) (0) | 2022.03.09 |
---|---|
Spring์ ์์กด์ฑ ์ฃผ์ (0) | 2022.03.09 |
์คํ๋ง์์ h2 ์ฌ์ฉ (0) | 2022.03.09 |
Lombok ์ค์น ๋ฐ ์ค๋ฅ ํด๊ฒฐ (0) | 2022.03.08 |
start.spring.io๋ก ํ๋ก์ ํธ ์์ฑ (0) | 2022.03.08 |