How to mock/unit test a Sling filter that does a redirect? (and other questions)
2 questions
- How I check if the redirect happens in my unit test?
- I cannot get a proper mock of an OSGI service that provides me access to an OSGI config. When I try to debug my unit test and the execution enters the filter, provider is null. How can I code it so it's not null?
some code (unit test + filter class + service)
my unit test
@ExtendWith(AemContextExtension.class)
class MaintenancePagePrincipalsFilterTest {
private static final String MAINTENANCE_MODE_FLAG_TRUE = "true";
private static final String MAINTENANCE_PATH_PATH = "/content/myapp/sg/en/maintenance.html";
@Mock
private HttpServletRequest request;
@Mock
private HttpServletResponse response;
@Mock
private FilterChain chain;
private MaintenanceModeConfigurationProvider provider;
private final AemContext context = new AemContext();
private MaintenancePageFilter filter;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
provider = mock(MaintenanceModeConfigurationProvider.class);
context.registerService(MaintenanceModeConfigurationProvider.class, provider);
filter = new MaintenancePageFilter();
}
@2785667
void MaintenanceModeEnabled() throws IOException, ServletException { when(provider.getMaintenanceModeFlag()).thenReturn(MAINTENANCE_MODE_FLAG_TRUE); when(provider.getMaintenancePagePath()).thenReturn(MAINTENANCE_PATH_PATH);
filter.doFilter(request, response, chain);
verify(response).sendRedirect(MAINTENANCE_PATH_PATH);
verify(chain, never()).doFilter(request, response);
}
}filter class
public class MaintenancePageFilter implements Filter {
@3214626
private MaintenanceModeConfigurationProvider provider;
@9944223
public void init(FilterConfig filterConfig) throws ServletException { }
@9944223
public void destroy() { }
@9944223
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException {
try {
if (StringUtils.isNotBlank(provider.getMaintenanceModeFlag())
&& StringUtils.isNotBlank(provider.getMaintenancePagePath()) {
((HttpServletResponse) response).sendRedirect(
provider.getMaintenancePagePath());
return;
}
} catch (IOException exception) {
} catch (IllegalStateException exception) {
}
chain.doFilter(request, response);
}
}service class to access OSGI config
public class MaintenanceModeConfigurationProviderImpl implements MaintenanceModeConfigurationProvider {
private MaintenanceModeConfiguration config;
@580286
@9182423
protected void activate(MaintenanceModeConfiguration config) { this.config = config; }
@9944223
public String getMaintenanceModeFlag() { return config.maintenanceModeFlag(); }
@9944223
public String getMaintenancePagePath() { return config.maintenancePagePath(); }
}