有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring引导Restcontroller作为单元测试中的内部类(webmvctest)

是否有可能在测试上下文中声明RestController,最好是作为spring引导测试的内部类?我确实需要一个特定的测试设置它。我已经尝试过以下作为POC的简单示例:

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";
        }
    }

}

不过,通过MockMvc测试端点可以实现404。我错过什么了吗


共 (1) 个答案

  1. # 1 楼答案

    问题是,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 = []