top of page

Write unit tests for a custom filter added in spring’s security filter chain?

Updated: Sep 18, 2021

In Another blog post I have shown how we can write our own customized filter (How To extend Security Filter Chain in Spring Boot ?) and add it in the Spring Security Filter Chain. Here in this post I will show how we can write unit tests to test such a custom filter. I am using Mockito and Junit to write the unit tests.

We will Inject a Mocked object of the MySecurityConfig Spring Configuration Class where we had registered the Filter to spring container.

The Test class for MySecurityConfig:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mocks;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import static;
import static org.junit.Assert.assertThat
public class MyTest {
  private static final MySecurityConfig  mySecurityConfig = new  MySecurityConfig ();
  private MySpecialFilter  mySpecialFilter;
   public void securityConfig_initializes_with_success() {
       FilterRegistrationBean rbean =  mySecurityConfig.filter();
       String patterns = new String[1];
       String patterns1 = new String[1];
        patterns1[0] = "/api/v1/*";
        assertThat( patterns1 , is(rbean.getUrlPatterns().toArray( patterns )))    

Recent Posts

See All


bottom of page