MetricsServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { super.init(config); final ServletContext context = config.getServletContext(); if (null == registry) { final Object registryAttr = context.getAttribute(METRICS_REGISTRY); if (registryAttr instanceof MetricRegistry) { this.registry = (MetricRegistry) registryAttr; } else { throw new ServletException("Couldn't find a MetricRegistry instance."); } } this.allowedOrigin = context.getInitParameter(ALLOWED_ORIGIN); this.jsonpParamName = context.getInitParameter(CALLBACK_PARAM); setupMetricsModule(context); } MetricsServlet();  MetricsServlet(MetricRegistry registry); @Override void init(ServletConfig config); static final String RATE_UNIT; static final String DURATION_UNIT; static final String SHOW_SAMPLES; static final String METRICS_REGISTRY; static final String ALLOWED_ORIGIN; static final String METRIC_FILTER; static final String CALLBACK_PARAM; }
@Test public void constructorWithRegistryAsArgumentIsUsedInPreferenceOverServletConfig() throws Exception { final MetricRegistry metricRegistry = mock(MetricRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); when(servletConfig.getServletContext()).thenReturn(servletContext); final MetricsServlet metricsServlet = new MetricsServlet(metricRegistry); metricsServlet.init(servletConfig); verify(servletConfig, times(1)).getServletContext(); verify(servletContext, never()).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); }
@Test public void constructorWithRegistryAsArgumentUsesServletConfigWhenNull() throws Exception { final MetricRegistry metricRegistry = mock(MetricRegistry.class); final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); when(servletConfig.getServletContext()).thenReturn(servletContext); when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) .thenReturn(metricRegistry); final MetricsServlet metricsServlet = new MetricsServlet(null); metricsServlet.init(servletConfig); verify(servletConfig, times(1)).getServletContext(); verify(servletContext, times(1)).getAttribute(eq(MetricsServlet.METRICS_REGISTRY)); }
@Test(expected = ServletException.class) public void constructorWithRegistryAsArgumentUsesServletConfigWhenNullButWrongTypeInContext() throws Exception { final ServletContext servletContext = mock(ServletContext.class); final ServletConfig servletConfig = mock(ServletConfig.class); when(servletConfig.getServletContext()).thenReturn(servletContext); when(servletContext.getAttribute(eq(MetricsServlet.METRICS_REGISTRY))) .thenReturn("IRELLEVANT_STRING"); final MetricsServlet metricsServlet = new MetricsServlet(null); metricsServlet.init(servletConfig); }