java - 如何对 Spring ResourceHandlerRegistry 服务的静态资源进行单元测试

标签 java spring unit-testing spring-mvc

我正在尝试对新的 Spring MVC 项目进行单元测试。我通过了服务于 index.jsp 的家庭 Controller 测试。我正在尝试测试由我的 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 = []

最佳答案

像这样的标准配置

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

如果您执行获取“/resources/css/test.css”而不是“resources/css/test.css”,您将取回 css 文件。为什么期待前锋?

关于java - 如何对 Spring ResourceHandlerRegistry 服务的静态资源进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32276750/

相关文章:

python - Python 中的 Flask 测试——在 repo 中构建一个 API,通过 import_module 对其进行单元测试

Java SWT 表列删除

java - 递归背包Java

java - 使用注释的基本 Spring Web MVC 应用程序

java - 更新 Maven 依赖项

javascript - 当使用 AngularJS 登录后授权 header 不存在时,Spring Security 不会抛出错误

java - 启用 Java 断言不适用于 Eclipse Luna

java - 使用 java netbeans 程序打开各种文件

java - 单元测试 JPA 查询

unit-testing - 如何构建要进行单元测试的系统?