How do I unit test with servlet Filter that access other beans
I am trying to write a unit test for my "OncePerRequestFilter" filter. The problem is the Autowired bean appearing as null inside "public OncePerRequestFilter clientInterceptorFilter()" only in a unit test. The code snippets of my unit test and Filter class is copied below. Can somebody guide me how I can inject the dependent beans in Servlet filter.
My Unit test code goes here
@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);
}
}
My Filter class is below. Both "authService" and "config" are null inside "public OncePerRequestFilter clientInterceptorFilter() " function
@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);
}
}
};
}
}
java unit-testing spring-boot
add a comment |
I am trying to write a unit test for my "OncePerRequestFilter" filter. The problem is the Autowired bean appearing as null inside "public OncePerRequestFilter clientInterceptorFilter()" only in a unit test. The code snippets of my unit test and Filter class is copied below. Can somebody guide me how I can inject the dependent beans in Servlet filter.
My Unit test code goes here
@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);
}
}
My Filter class is below. Both "authService" and "config" are null inside "public OncePerRequestFilter clientInterceptorFilter() " function
@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);
}
}
};
}
}
java unit-testing spring-boot
Ofcourse it is. You are Creating the configuration yourself in the@Before
method outside of Spring, so it is just a regular method call. But this is hardly a unit test rather an Integrating test. If you want a unit test create the filter yourself, mock the needed dependencies and inject them. Also make it a proper class instead of inlining it like this.
– M. Deinum
Nov 13 '18 at 16:58
I think I am not following you. I need to test just filter implementation. @MockBean private IAuthServiceClient authService; trying to mock service. Also, used BDDMockito to mock the response. Are you saying I should remove @Before?
– Amna Irshad Sipra
Nov 13 '18 at 17:27
You want a unit test, but you are rather creating an integration test. Which. You totally bypass by creating your own instance of the configuration to obtain the filter. So which is it you want, an integration or a unit test? If you want a unit test it is easier to create a real class for the filter instead of inlining it.
– M. Deinum
Nov 13 '18 at 18:53
add a comment |
I am trying to write a unit test for my "OncePerRequestFilter" filter. The problem is the Autowired bean appearing as null inside "public OncePerRequestFilter clientInterceptorFilter()" only in a unit test. The code snippets of my unit test and Filter class is copied below. Can somebody guide me how I can inject the dependent beans in Servlet filter.
My Unit test code goes here
@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);
}
}
My Filter class is below. Both "authService" and "config" are null inside "public OncePerRequestFilter clientInterceptorFilter() " function
@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);
}
}
};
}
}
java unit-testing spring-boot
I am trying to write a unit test for my "OncePerRequestFilter" filter. The problem is the Autowired bean appearing as null inside "public OncePerRequestFilter clientInterceptorFilter()" only in a unit test. The code snippets of my unit test and Filter class is copied below. Can somebody guide me how I can inject the dependent beans in Servlet filter.
My Unit test code goes here
@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);
}
}
My Filter class is below. Both "authService" and "config" are null inside "public OncePerRequestFilter clientInterceptorFilter() " function
@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);
}
}
};
}
}
java unit-testing spring-boot
java unit-testing spring-boot
asked Nov 13 '18 at 16:38
Amna Irshad SipraAmna Irshad Sipra
817
817
Ofcourse it is. You are Creating the configuration yourself in the@Before
method outside of Spring, so it is just a regular method call. But this is hardly a unit test rather an Integrating test. If you want a unit test create the filter yourself, mock the needed dependencies and inject them. Also make it a proper class instead of inlining it like this.
– M. Deinum
Nov 13 '18 at 16:58
I think I am not following you. I need to test just filter implementation. @MockBean private IAuthServiceClient authService; trying to mock service. Also, used BDDMockito to mock the response. Are you saying I should remove @Before?
– Amna Irshad Sipra
Nov 13 '18 at 17:27
You want a unit test, but you are rather creating an integration test. Which. You totally bypass by creating your own instance of the configuration to obtain the filter. So which is it you want, an integration or a unit test? If you want a unit test it is easier to create a real class for the filter instead of inlining it.
– M. Deinum
Nov 13 '18 at 18:53
add a comment |
Ofcourse it is. You are Creating the configuration yourself in the@Before
method outside of Spring, so it is just a regular method call. But this is hardly a unit test rather an Integrating test. If you want a unit test create the filter yourself, mock the needed dependencies and inject them. Also make it a proper class instead of inlining it like this.
– M. Deinum
Nov 13 '18 at 16:58
I think I am not following you. I need to test just filter implementation. @MockBean private IAuthServiceClient authService; trying to mock service. Also, used BDDMockito to mock the response. Are you saying I should remove @Before?
– Amna Irshad Sipra
Nov 13 '18 at 17:27
You want a unit test, but you are rather creating an integration test. Which. You totally bypass by creating your own instance of the configuration to obtain the filter. So which is it you want, an integration or a unit test? If you want a unit test it is easier to create a real class for the filter instead of inlining it.
– M. Deinum
Nov 13 '18 at 18:53
Ofcourse it is. You are Creating the configuration yourself in the
@Before
method outside of Spring, so it is just a regular method call. But this is hardly a unit test rather an Integrating test. If you want a unit test create the filter yourself, mock the needed dependencies and inject them. Also make it a proper class instead of inlining it like this.– M. Deinum
Nov 13 '18 at 16:58
Ofcourse it is. You are Creating the configuration yourself in the
@Before
method outside of Spring, so it is just a regular method call. But this is hardly a unit test rather an Integrating test. If you want a unit test create the filter yourself, mock the needed dependencies and inject them. Also make it a proper class instead of inlining it like this.– M. Deinum
Nov 13 '18 at 16:58
I think I am not following you. I need to test just filter implementation. @MockBean private IAuthServiceClient authService; trying to mock service. Also, used BDDMockito to mock the response. Are you saying I should remove @Before?
– Amna Irshad Sipra
Nov 13 '18 at 17:27
I think I am not following you. I need to test just filter implementation. @MockBean private IAuthServiceClient authService; trying to mock service. Also, used BDDMockito to mock the response. Are you saying I should remove @Before?
– Amna Irshad Sipra
Nov 13 '18 at 17:27
You want a unit test, but you are rather creating an integration test. Which. You totally bypass by creating your own instance of the configuration to obtain the filter. So which is it you want, an integration or a unit test? If you want a unit test it is easier to create a real class for the filter instead of inlining it.
– M. Deinum
Nov 13 '18 at 18:53
You want a unit test, but you are rather creating an integration test. Which. You totally bypass by creating your own instance of the configuration to obtain the filter. So which is it you want, an integration or a unit test? If you want a unit test it is easier to create a real class for the filter instead of inlining it.
– M. Deinum
Nov 13 '18 at 18:53
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53285629%2fhow-do-i-unit-test-with-servlet-filter-that-access-other-beans%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53285629%2fhow-do-i-unit-test-with-servlet-filter-that-access-other-beans%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Ofcourse it is. You are Creating the configuration yourself in the
@Before
method outside of Spring, so it is just a regular method call. But this is hardly a unit test rather an Integrating test. If you want a unit test create the filter yourself, mock the needed dependencies and inject them. Also make it a proper class instead of inlining it like this.– M. Deinum
Nov 13 '18 at 16:58
I think I am not following you. I need to test just filter implementation. @MockBean private IAuthServiceClient authService; trying to mock service. Also, used BDDMockito to mock the response. Are you saying I should remove @Before?
– Amna Irshad Sipra
Nov 13 '18 at 17:27
You want a unit test, but you are rather creating an integration test. Which. You totally bypass by creating your own instance of the configuration to obtain the filter. So which is it you want, an integration or a unit test? If you want a unit test it is easier to create a real class for the filter instead of inlining it.
– M. Deinum
Nov 13 '18 at 18:53