Spring控制器ModelAndView测试MockMvc空响应

Spring Controller ModelAndView test MockMvc empty Response

我将这个简单的示例设置为单元测试 spring Controller ModelAndView with MockMvc,但响应始终为空,即使在调试中我可以看到控制器代码已执行。

代码如下:

/src/main/java/controller/MvcController.java

package controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MvcController {

    @RequestMapping("/hello/{id}")
    public ModelAndView hello(@PathVariable("id") String id) {
        Map<String, String> model = new HashMap<>();
        ModelAndView modelAndView = new ModelAndView("hello", model);
        return modelAndView;
    }

}

/src/main/webapp/WEB-INF/jsp/hello.jsp

<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="e"
    uri="https://www.owasp.org/index.php/OWASP_Java_Encoder_Project"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>HELLO WORLD
    </body>
</html>

/src/test/java/controller/MvcControllerTest.java

package controller;

import static org.assertj.core.api.Assertions.assertThat;

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.mock.web.MockHttpServletResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MvcController.class })
public class MvcControllerTest {

    @Autowired
    private MvcController mvcController;

    private MockMvc mockMvc;

    @Before
    public void init() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/jsp/");
        resolver.setSuffix(".jsp");
        this.mockMvc = MockMvcBuilders.standaloneSetup(mvcController).setViewResolvers(resolver).build();
    }

    @Test
    public void testHello() throws Exception {
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get("/hello/XWQHEDg9e72t");
        ResultActions result = mockMvc.perform(requestBuilder);
        MvcResult mvcResult = result.andReturn();
        MockHttpServletResponse mockHttpServletResponse = mvcResult.getResponse();
        String response = mockHttpServletResponse.getContentAsString();
        assertThat(response).contains("HELLO WORLD");
    }

}

MockMvc中的关键字是mock。此框架未设置带有 JSP 引擎的完整 Servlet 容器。因此,它不会呈现您的控制器 returns 和 MockHttpServletResponse 不包含正文(对于此用例)的视图。

您可以使用 MockHttpServletResponse#getForwardedUrl() 获取 Servlet 容器将请求转发到的 JSP 的 url,由您的视图名称以及前缀和后缀构成你的 InternalResourceViewResolver.