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 org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat
(Runwith=MockitoJUnitRunner.Class)
public class MyTest {
@InjectMocks
private static final MySecurityConfig mySecurityConfig = new MySecurityConfig ();
@Mock
private MySpecialFilter mySpecialFilter;
@Test
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 )))
}
}
Comentarios