Spring Boot Restcontroller как внутренний класс в модульном тесте (webmvctest) - PullRequest
1 голос
/ 24 февраля 2020

Возможно ли как-то объявить RestController в контексте теста, предпочтительно как внутренний класс теста с весенней загрузкой? Мне это нужно для конкретной настройки теста c. Я уже попробовал следующий простой пример в качестве PO C:

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.client.AutoConfigureWebClient;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;


@ExtendWith(SpringExtension.class)
@WebMvcTest(ExampleTest.TestController.class)
@AutoConfigureMockMvc
@AutoConfigureWebClient
public class ExampleTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void exampleTest() throws Exception {
        ResultActions resultActions = this.mockMvc
                .perform(get("/test"));
        resultActions
                .andDo(print());
    }

    @RestController
    public static class TestController {
        @GetMapping("/test")
        public String test() {
            return "hello";
        }
    }

}

. Тестирование конечной точки через Mock Mvc дает 404. Я что-то упустил?

1 Ответ

1 голос
/ 24 февраля 2020

Проблема в том, что TestController не загружен в контекст приложения. Это можно решить, добавив

@ ContextConfiguration (classes = ExampleTest.TestController.class)

Тест будет выглядеть следующим образом:

@ExtendWith(SpringExtension.class)
@WebMvcTest(ExampleTest.TestController.class)
@ContextConfiguration(classes= ExampleTest.TestController.class)
@AutoConfigureMockMvc
@AutoConfigureWebClient
public class ExampleTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void exampleTest() throws Exception {
        ResultActions resultActions = this.mockMvc
                .perform(get("/test"));
        resultActions
                .andDo(print());
    }

    @RestController
    public static class TestController {
        @GetMapping("/test")
        public String test() {
            return "hello";
        }
    }

}

И вывод:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"text/plain;charset=UTF-8", Content-Length:"5"]
     Content type = text/plain;charset=UTF-8
             Body = hello
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
...