加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何单元测试Spring ResourceHandlerRegistry提供的静态

发布时间:2020-12-15 00:35:11 所属栏目:Java 来源:网络整理
导读:我正在尝试对一个新的 Spring MVC项目进行单元测试.我有一个服务于index.jsp的家庭控制器的通过测试.我正在尝试在WebConfig中测试由ResourceHandlerRegistry提供的静态资源. 有关如何正确执行此操作的任何提示?以下是我的代码: @RunWith(SpringJUnit4Class
我正在尝试对一个新的 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 = []

解决方法

使用标准配置
<mvc:resources mapping="/resources/**" location="/resources/"/>

如果你执行get“/resources/css/test.css”而不是“resources / css / test.css”,你将获得css文件.你为什么期待前锋?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读