Java – how to unit test static resources provided by spring resourcehandlerregistry
•
Java
I'm trying to unit test a new spring MVC project I have a service for index JSP home controller passed the test I am trying to test the static resources provided by resourcehandlerregistry in webconfig
Any tips on how to do this correctly? Here 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 of 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 = []
Solution
Use standard configuration
<mvc:resources mapping="/resources/**" location="/resources/"/>
If you execute get "/ resources / CSS / test. CSS" instead of "resources / CSS / test. CSS", you will get the CSS file Why do you expect strikers?
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码