使用Spring-boot时,如何在测试中改写servlet?

时间:2019-05-30 16:03:46

标签: spring-boot servlets

使用@ServletComponentScan时如何在junit测试中替代Servlet?

我有一个Spring-boot Web应用程序,它按如下方式加载Servlet设置;


@SpringBootApplication
@ServletComponentScan({"my.example"})
public class MyServer extends SpringBootServletInitializer {
    public static void main(String[] args) {
        SpringApplication.run(MyServer.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyServer.class);
    }
}



package my.example;

@WebServlet(
        urlPatterns = "/myserver",
        initParams =
                {
                        @WebInitParam(name = "testParam", value = "x")
                }
)
package my.example;

public class MyServlet extends HttpServlet {
  ...
}

在此Web应用程序中,正在使用initParam'testParam'='x'加载servlet。

我正在尝试编写一个测试,其中使用initParam'testParam'='y'加载servlet。

以下是测试的代码。



@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyServer.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyServerTest {
    ...
}


package my.example;

@Primary
@WebServlet(
        urlPatterns = "/myserver",
        initParams =
                {
                        @WebInitParam(name = "testParam", value = "y")
                }
)
public class MyTestServlet extends MyServlet {
}

但是,不会加载MyTestServlet。我该如何解决?

0 个答案:

没有答案