如何在Spring中测试自定义WebApplicationInitializer

时间:2019-07-11 14:41:23

标签: spring-boot spring-mvc spring-test

我将web.xml移至Java注释配置

我的自定义代码是

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/*");
}

我尝试了解决方法https://stackoverflow.com/a/25210356/6700081,但行覆盖率仍为0%

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,并以此方式解决了:

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..
}}

注意:我使用Junit5(@BeforeEach)