Matthias M
Matthias M

Reputation: 14890

Spring MockMvc: How to access Request Object while initializing test

I need to access the request of my mockMvc for initializing.

@Before
public void setup() {
  this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac.build());

  // TODO how to get request out of mockMvc?
  request = ???      

  SomeUtils.init(request)
}

@Test
public void test() throws Exception {   
  final ResultActions result = this.mockMvc.perform(uri);
}

I tried to use an own RequestBuilder. But this doesn't work. I can provide more details, if you think this is the right solution.

... .defaultRequest(new RequestBuilder() { ...

PS Don't blame me for using static methods. It's third party code!

Upvotes: 1

Views: 497

Answers (1)

orlanthi
orlanthi

Reputation: 212

I'm using Spring 3 so your mileage may vary but I ended up doing this by creating a custom javax.servlet.Filter and adding it to the MockMvcBuilders object using the addFilter method.

 .addFilter(new Filter() {
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          SomeUtils.init(request)
          chain.doFilter(request, response);
        }
        ...
      })

(Would love to know if there is a better way though.)

Upvotes: 2

Related Questions