Program Club

Spring Boot Controller 엔드 포인트에 대한 단위 테스트를 작성하는 방법

proclub 2020. 11. 8. 11:29
반응형

Spring Boot Controller 엔드 포인트에 대한 단위 테스트를 작성하는 방법


다음과 같은 샘플 Spring Boot 앱이 있습니다.

부트 메인 클래스

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

제어 장치

@RestController
@EnableAutoConfiguration
public class HelloWorld {
    @RequestMapping("/")
    String gethelloWorld() {
        return "Hello World!";
    }

}

컨트롤러에 대한 단위 테스트를 작성하는 가장 쉬운 방법은 무엇입니까? 나는 다음을 시도했지만 WebApplicationContext를 autowire하지 못하는 것에 대해 불평합니다.

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {

    final String BASE_URL = "http://localhost:8080/";

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception{

         this.mockMvc.perform(get("/")
                 .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                 .andExpect(status().isOk())
                 .andExpect(content().contentType("application/json"));
    }

    @Test
    public void contextLoads() {
    }

}

Spring MVC는 컨텍스트 없이도 비교적 간단한 컨트롤러 테스트를 지원 하는 standaloneSetup제공합니다 .

하나 이상의 @Controller 인스턴스를 등록하고 프로그래밍 방식으로 Spring MVC 인프라를 구성하여 MockMvc를 빌드하십시오. 이를 통해 일반 단위 테스트와 유사하게 컨트롤러의 인스턴스화 및 초기화 및 종속성을 완전히 제어 할 수 있으며 동시에 한 번에 하나의 컨트롤러를 테스트 할 수 있습니다.

컨트롤러에 대한 예제 테스트는 다음과 같이 간단 할 수 있습니다.

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/")
           .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"));

    }
}

Spring Boot에서 데뷔 한 새로운 테스트 개선 사항은 1.4.M2이와 같은 상황을 작성하는 데 필요한 코드의 양을 줄이는 데 도움이 될 수 있습니다.

테스트는 다음과 같습니다.

import static org.springframework.test.web.servlet.request.MockMvcRequestB‌​uilders.get; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat‌​chers.content; 
import static org.springframework.test.web.servlet.result.MockMvcResultMat‌​chers.status;

    @RunWith(SpringRunner.class)
    @WebMvcTest(HelloWorld.class)
    public class UserVehicleControllerTests {

        @Autowired
        private MockMvc mockMvc;

        @Test
        public void testSayHelloWorld() throws Exception {
            this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType("application/json"));

        }

    }

자세한 내용과 설명서 블로그 게시물을 참조하십시오.


다음은 Spring MVC의 standaloneSetup을 사용하는 또 다른 답변입니다. 이 방법을 사용하여 컨트롤러 클래스를 자동 연결하거나 Mock 할 수 있습니다.

    import static org.mockito.Mockito.mock;
    import static org.springframework.test.web.server.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.server.result.MockMvcResultMatchers.content;
    import static org.springframework.test.web.server.result.MockMvcResultMatchers.status;

    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.http.MediaType;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    import org.springframework.test.web.server.MockMvc;
    import org.springframework.test.web.server.setup.MockMvcBuilders;


    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
    public class DemoApplicationTests {

        final String BASE_URL = "http://localhost:8080/";

        @Autowired
        private HelloWorld controllerToTest;

        private MockMvc mockMvc;

        @Before
        public void setup() {
            this.mockMvc = MockMvcBuilders.standaloneSetup(controllerToTest).build();
        }

        @Test
        public void testSayHelloWorld() throws Exception{
            //Mocking Controller
            controllerToTest = mock(HelloWorld.class);

             this.mockMvc.perform(get("/")
                     .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                     .andExpect(status().isOk())
                     .andExpect(content().mimeType(MediaType.APPLICATION_JSON));
        }

        @Test
        public void contextLoads() {
        }

    }

DemoApplicationTests 클래스에 @WebAppConfiguration( org.springframework.test.context.web.WebAppConfiguration) 주석을 추가 하면 작동합니다.

참고 URL : https://stackoverflow.com/questions/29053974/how-to-write-a-unit-test-for-a-spring-boot-controller-endpoint

반응형