Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring filter chain is not applied on unit test MockMvc

I made a custom filter and registered on WebConfig, but when I call the api, the filter does not get invoked. I looked through the log, and seems like filter chain I described on the config is not applied. However I checked WebConfig is invoked using debugger.

//MyFilter.java
@Component
public class MyFilter implements Filter {
  @Override
  doFilter(...) { // This part is NOT getting invoked
    ...
  }
}
//WebConfig.java
@Configuration
public class WebConfig {
  @Bean
  public FilterRegistrationBean<MyFilter> myFilter() { // This part is getting invoked
    regBean = new FilterRegistrationBean();
    regBean.setFilter(new MyFilter());
    regBean.setOrder(0);
    return regBean;
  }
}
//MyTest.java
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyApplication.class)
public class MyTest {
  
  private MockMvc mockMvc;

  @Autowired
  WebApplicationContext ctx;

  @Before
  public void before() {
    mockMvc = MockMvcBuilders.webApplicationSetup(ctx).build();
  }

  @Test
  public void doTest() {
    mockMvc.perform(...);
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this.mockMvc = MockMvcBuilders.webApplicationSetup(ctx)
            .addFilters(filter).build();

If you don’t use @AutoConfiguraMockMvc then you have to add filters to mockMvc builder.

What's required to make mockMVC test a filter's init routine?

Also there is a configuration problem here.

@Bean
  public FilterRegistrationBean<MyFilter> myFilter(MyFilter myfilter) { // This part is getting invoked
    regBean = new FilterRegistrationBean();
    regBean.setFilter(myFilter);
    regBean.setOrder(0);
    return regBean;
  }

You are putting new Instance of a filter to filter chain but you create singleton filter. You can use above configuration.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading