问题
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