0

I moved web.xml to Java annotation configuration

My custom code is

public class WebInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setDisplayName("app-name");
    context.register(Config.class);
    container.addListener(new RequestContextListener());
    container.addListener(new ContextLoaderListener(context));

    Dynamic dispatcher = container.addServlet("app-name", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/app-name-rest/*");
}

I tried the solution https://stackoverflow.com/a/25210356/6700081 but the line coverage is still 0%

firstpostcommenter
  • 2,328
  • 4
  • 30
  • 59

1 Answers1

0

I had the same problem and solved in this way:

public class WebInitializerTest {

@Mock
private MockServletContext mockServletContext;

@Mock
private ServletRegistration.Dynamic mockServletRegistration;

@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testOnStartup() {
    WebInitializer webInitializer = new WebInitializer();
    when(mockServletContext.addServlet(ArgumentMatchers.eq("app-name"), any(Servlet.class))).thenReturn(mockServletRegistration);

    webInitializer.onStartup(mockServletContext);

    verify(mockServletContext, times(1)).addListener(any(RequestContextListener.class));
    // other asserts..
}}

Note: I use Junit5 (@BeforeEach)

Marc
  • 2,738
  • 1
  • 17
  • 21