【问题标题】:How to Unit Test static resources served by Spring ResourceHandlerRegistry如何对 Spring ResourceHandlerRegistry 提供的静态资源进行单元测试
【发布时间】:2015-11-23 10:50:33
【问题描述】:

我正在尝试对一个新的 Spring MVC 项目进行单元测试。我对服务 index.jsp 的家庭控制器进行了通过测试。我正在尝试在我的 WebConfig 中测试由 ResourceHandlerRegistry 提供的静态资源。

关于如何正确执行此操作的任何提示?以下是我的代码:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebConfig.class})
public class HomeControllerTest {

private MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;

@Before
public void setUp() throws Exception {
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
                            .build();
}

@Test
public void testGetHomepage() throws Exception { //passing :)
    this.mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andExpect(forwardedUrl("/WEB-INF/pages/index.jsp"));
}

@Test
public void testGetResources() throws Exception {   // TEST FAILS :( with 404
    this.mockMvc.perform(get("resources/css/test.css"))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(forwardedUrl("/resources/css/test.css"));
}

}

print() 的输出:

    2015-08-28 12:53:09 WARN  PageNotFound:1136 - No mapping found for HTTP request with URI [resources/css/test.css] in DispatcherServlet with name ''

MockHttpServletRequest:
     HTTP Method = GET
     Request URI = resources/css/test.css
      Parameters = {}
         Headers = {}

         Handler:
            Type = null

           Async:
   Async started = false
    Async result = null

  Resolved Exception:
            Type = null

    ModelAndView:
       View name = null
            View = null
           Model = null

        FlashMap:

MockHttpServletResponse:
          Status = 404
   Error message = null
         Headers = {}
    Content type = null
            Body = 
   Forwarded URL = null
  Redirected URL = null
         Cookies = []

【问题讨论】:

    标签: java spring unit-testing spring-mvc


    【解决方案1】:

    这样的标准配置
    <mvc:resources mapping="/resources/**" location="/resources/"/>
    

    如果您执行 get "/resources/css/test.css" 而不是 "resources/css/test.css",您将取回 css 文件。你为什么期待一个前锋?

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 2018-03-16
      • 2016-05-04
      • 2021-10-11
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多