mockmvc Load Redirect URL

安稳与你 提交于 2020-03-22 06:23:34

问题


I am writing test for a Spring Rest Service which redirects the url to another spring service. So the goal is to find the Bookmark using a bookmark name. The first service gets the BookmarkId using the Bookmark name and then it redirects the url to load the object based on the BookmarkId

I can easily test the url redirect using, the below works fine

 mockMvc.perform(get("/bookmarks/name/" + "sample"))
                .andExpect(status().isMovedPermanently()).andExpect(redirectedUrl("/bookmarks/" + bookmark.getKey()));

what I want is to do the next step and call the next url and load the bookmark object, how do I do that ??


回答1:


Just do what a web browser would do - follow the redirection by requesting the URL you get in Location header:

mockMvc.perform(get("/bookmarks/" + bookmark.getKey())).andExpect(...)

This is a separate testcase though. So one TC should test if you actually get redirected, and the other one that tests the bookmarks/{id} endpoint.

EDIT (13 June 2017)

There is a feature request in Spring Framework's bugtracker to allow MockMVC to follow redirects (SPR-14342 Improve MockMvc to follow redirects and forwards). It's been rejected early this year though with the following comment:

Resolving as "Won't Fix" since general support for forwarding is well beyond the scope of the MockHttpServletRequest. Consider testing directly against the forwarded URL and setting up the request as it would be expected at the point of forwarding.



来源:https://stackoverflow.com/questions/40225479/mockmvc-load-redirect-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!