Returning to Java/Spring after many years away. Trying to develop a controller test. I want test a handler for an OPTIONS request, but when I use MockMvc to do something like
MockHttpServletRequestBuilder optionsRequest = options("/endpoint/1234");
optionsRequest.header("Origin", "http://blah");
this.mockMvc.perform(optionsRequest).
andExpect(status().isOk()).
andExpect(header().string("Access-Control-Allow-Credentials", "application/json")).
andExpect(header().string("Access-Control-Allow-Origin", "application/json")).
andExpect(header().string("Access-Control-Allow-Methods", "application/json")).
andExpect(header().string("Access-Control-Allow-Headers", "application/json"));
with setup
this.mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
where controller is an instance of my controller, the options handler never gets fired.
In my server startup, we need to do this
dispatcherServlet.setDispatchOptionsRequest(true);
to get the requests handled in the running application.
Is there a way to access the dispatcher servlet in the test setup so I can set the same option?
I have fallen back to setting up mock request/response objects and invoking the methods manually for now....
You can simply create your MockMvc object with that option
this.mockMvc = MockMvcBuilders.standaloneSetup(this.controller)
.dispatchOptions(true)
.build();
Here's the javadoc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With