如何使用访问其他bean的servlet过滤器进行单元测试

时间:2018-11-13 16:38:40

标签: java unit-testing spring-boot

我正在尝试为“ OncePerRequestFilter”过滤器编写单元测试。问题是仅在单元测试中,自动装配的bean在“ public OncePerRequestFilter clientInterceptorFilter()”内部显示为空。我的单元测试和Filter类的代码片段复制如下。有人可以指导我如何在Servlet过滤器中注入依赖的bean。

我的单元测试代码在这里

@RunWith(SpringRunner.class)
@ImportAutoConfiguration({ RefreshAutoConfiguration.class })
@TestPropertySource(locations = "classpath:application.properties")
@Import({ FilterConfig.class, IAuthServiceClient.class, AppConfig.class })
// @TestExecutionListeners({
// DependencyInjectionTestExecutionListener.class,
// DirtiesContextTestExecutionListener.class})
public class FilterConfigTest implements AppConstants {

    @MockBean
    private IAuthServiceClient authService;

    @Autowired
    FilterConfig config;

    @Autowired
    ResourceLoader loader;

    @Autowired
    AppConfig appconfig;

    private MockHttpServletRequest  request;
    private MockHttpServletResponse response;
    private MockFilterChain         chain;
    private OncePerRequestFilter    filter;

    @SuppressWarnings("serial")
    @Before
    public void setUp() throws Exception {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        chain = new MockFilterChain();
        filter = new FilterConfig().clientInterceptorFilter();

    }
    @Test
    public void validTokenTest() throws IOException, ServletException {
        BDDMockito.given(authService.getPrincipal(anyString(), anyList())).willReturn(getStubbedPrincipal());
        this.request.addHeader(HttpHeaders.AUTHORIZATION, "sometoken");
        this.request.addHeader(XH_AUTH_HEADER, "someauthheader");
        this.filter.doFilter(this.request, this.response, this.chain);
    }
}

我的过滤器类如下。在“ public OncePerRequestFilter clientInterceptorFilter()”函数中,“ authService”和“ config”均为空

 @Configuration
    public class FilterConfig implements AppConstants {
        @Autowired
        private IAuthServiceClient authService;

        @Autowired
        AppConfig config;

        private final static Logger logger = LoggerFactory.getLogger(FilterConfig.class);


        @Bean
        public OncePerRequestFilter clientInterceptorFilter() {
            return new OncePerRequestFilter() {
                @Override
                protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                        FilterChain filterChain) throws ServletException, IOException {
                    String authorization = Optional.ofNullable(request.getHeader(HttpHeaders.AUTHORIZATION)).orElse(null);
                    String xhAuth = Optional.ofNullable(request.getHeader(XH_AUTH_HEADER)).orElse(null);
                    List<String> scopes = config.getscopesAsList();

                    try {
                        Principal principal = authService.getPrincipal(authorization, scopes);
                        if(principal != null) {
                         //do something
                          filterChain.doFilter(request, response);
                        }

                    } catch (Exception e) {

                       throw new NoAuthorizedPrincipalFound(HttpStatus.UNAUTHORIZED, INVALID_AUTOIRIZED_PRINCIPAL);

                    }

                }
            };
        }

    }

0 个答案:

没有答案