Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom filter not injected in Spring integration test

I have an integration test that is designed to start my Spring Boot app:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AppConfigCorrelationIdTestIt.class)
@WebIntegrationTest("server.port:0")
public class CorrelationIdTestIT {

Where the configuration class is:

@EnableConfigurationProperties
@ComponentScan
@EnableAutoConfiguration
@Configuration
public class AppConfigCorrelationIdTestIt {

In the app I have a defined custom servlet filter:

public class CorrelationHeaderFilter implements Filter {

But when testing my app I'm finding that the customer filter isn't instantiated and injected in to the filter chain. The only way round this I've found is to manually create it as a bean in AppConfigCorrelationIdTestIt, and then it works perfectly.

@Bean
public CorrelationHeaderFilter correlationHeaderFilter() {
    return new CorrelationHeaderFilter();
}

Any ideas why the filter isn't picked up by Spring Boot when the application starts?

Thanks

like image 836
nickcodefresh Avatar asked Oct 28 '15 17:10

nickcodefresh


1 Answers

Usually, in test classes possible to use DefaultMockMvcBuilder.addFilter(Filter filter, String... urlPatterns) when configured MockMvc. For example:

@WebAppConfiguration
@ContextConfiguration
public class AuthenticationTest {

private static final String TOKEN_HEADER = "X-Firebase-Auth";

final String url = "http://localhost:8080/authentication";

final Logger logger = LoggerFactory.getLogger(AuthenticationTest.class);

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
public Filter springSecurityFilterChain;

private MockMvc mockMvc;

@Before
public void setUp(){
    mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
            .addFilter(springSecurityFilterChain).build();
}
...

}

I based on this answer

like image 183
Maksim Ryabovol Avatar answered Sep 21 '22 08:09

Maksim Ryabovol