使用@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。我该如何解决?