我有这个过滤器类,并且在使用junit进行测试时需要具有尽可能高的代码覆盖率。
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String userId= request.getHeader(Constants.USER_ID);
if (StringUtils.isEmpty(userId)) {
LOGGER.error("User Id is missing in request header.");
isAuthorized = false;
}
if (!isAuthorized) {
LOGGER.warn("Authorization failed: User ID =[{}] is not authorized to access.", userId);
response.setContentType("text/html; charset=UTF-8");
response.getWriter().write(errorMsg);
} else {
filterChain.doFilter(request, response);
}
}
和测试班:
@RunWith(MockitoJUnitRunner.class)
public class SampleFilterTest {
@Mock
FilterConfig filterConfig;
ServletRequest servletRequest;
ServletResponse servletResponse;
HttpServletRequest request;
@Mock
FilterChain filterChain;
@Mock
HttpServletResponse httpServletResponse;
@InjectMocks
SampleFilter sampleFilter;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void init() throws ServletException {
sampleFilter.init(filterConfig);
}
@Test
public void doFilter() throws IOException, ServletException{
//when(request.getHeader(Constants.USER_ID)).thenReturn("batman");
sampleFilter.doFilter(servletRequest, servletResponse, filterChain);
}
@Test
public void destroy() {
sampleFilter.destroy();
}
}
当我运行doFilter()
时,它会在
NullPointerException
String userId= request.getHeader(Constants.USER_ID);
行。
如何避免这种情况?
我需要调用此方法并执行内部内容以提供所需的代码覆盖范围。
答案 0 :(得分:1)
问题是
HttpServletRequest request = (HttpServletRequest) servletRequest;
强制转换为 null ,因为您传入的ServletRequest
不会强制转换为HttpServletRequest
模拟要尝试将其强制转换为被测方法中的实际类型。
例如
//...
@Test
public void doFilter() throws IOException, ServletException {
//Arrange
//mock HttpServletResponse so cast does not fail
ServletRequest request = mock(HttpServletRequest.class);
when(request.getHeader(Constants.USER_ID)).thenReturn("batman");
ServletResponse response = mock(HttpServletResponse.class);
//setup response as neded. Looks like `.getWriter().write(errorMsg);` needs mocking
//Act
sampleFilter.doFilter(request, response, filterChain);
//Assert
//...
}