๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Spring

MockMvc - ๊ฐ„๋‹จํ•œ ํ…Œ์ŠคํŠธ ์ฝ”๋“œ

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 ๊ฒฐ๊ณผ ํ™•์ธ


ํ…Œ์ŠคํŠธ๋ฅผ ๋Œ๋ ค๋ณด๊ณ  ์„ฑ๊ณตํ•˜๋ฉด ์œ„์™€ ๊ฐ™์€ ์ดˆ๋ก ๋ฒ„ํŠผ๊ณผ ๋ฉ”์‹œ์ง€๊ฐ€ ์ถœ๋ ฅ๋œ๋‹ค.

ํ…Œ์ŠคํŠธ์— ์‹คํŒจํ•˜๋ฉด ๋นจ๊ฐ„ ๋ฒ„ํŠผ์ด ๋‚˜์˜จ๋‹ค.