Hugh
Hugh

Reputation: 1163

Can I test servlet filters with REST Assured?

I have a Spring Boot MVC app with a @WebFilter that adds a custom header to every response. It works fine when I actually run the app, but I'm a little surprised that the filter doesn't run during my REST Assured test.

There's nothing fancy in my test; it basically reduces to

RestAssuredMockMvc.standaloneSetup(new MyController());
boolean headerExists = given().when().get().headers().hasHeaderWithName("my-header");

Is this expected? Should I be doing something extra to set up the filter chain?

Upvotes: 1

Views: 1351

Answers (2)

andreu
andreu

Reputation: 66

You can do it as this:

StandaloneMockMvcBuilder builder = MockMvcBuilders.standaloneSetup(yourController);
builder.addFilters(new YourFilter());
RestAssuredMockMvc.standaloneSetup(builder);

Upvotes: 0

Simon Martinelli
Simon Martinelli

Reputation: 36143

MockMvc is an infrastructure to test your controllers and not the full web container.

If you want to have the filters working you have to add it. This would look something like:

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setUp() {
   Collection<Filter> filterCollection = wac.getBeansOfType(Filter.class).values();
   Filter[] filters = filterCollection.toArray(new Filter[filterCollection.size()]);
   mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(filters).build();
}

Upvotes: 2

Related Questions