简体   繁体   中英

How to Unit Test static resources served by Spring ResourceHandlerRegistry

I'm trying to unit test a new Spring MVC project. I have a passing test for the home controller serving index.jsp. I'm trying to test serving static resources served by the ResourceHandlerRegistry in my WebConfig.

Any tips on how to do this correctly? Below is my code:

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

}

Output from 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 = []

With a standard configuration like

<mvc:resources mapping="/resources/**" location="/resources/"/>

if you perform a get "/resources/css/test.css" instead of "resources/css/test.css" you will get back the css file. Why do you expect a forward?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM