5

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 ??

developer2015
  • 399
  • 8
  • 25

1 Answers1

6

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.

jannis
  • 4,843
  • 1
  • 23
  • 53
  • yeah I am already doing that was wondering if these two steps could be combined into one – developer2015 Oct 25 '16 at 01:57
  • For now it's not possible with MockMvc. It is being considered to allow `MockMvc` to follow redirects: [SPR-14342](https://jira.spring.io/browse/SPR-14342). For now you could use [MockMvcWebConnection](http://docs.spring.io/spring-test-htmlunit/docs/current/api/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnection.html). Note that this is a completely different API though. I'll update my answer with an example later if I find a minute. – jannis Oct 25 '16 at 08:20
  • It's a shame this isn't a supported use-case. The amount of setup work required for a simple "authenticate then redirect" flow is significantly higher if the only solution is to hit the forwarded URL directly (think session ids). – MrJohnBBQ Jan 30 '19 at 05:04