我需要我的 Spring Boot Web 应用程序在 JUnit 中重新启动
Posted
技术标签:
【中文标题】我需要我的 Spring Boot Web 应用程序在 JUnit 中重新启动【英文标题】:I need my Spring Boot WebApplication to restart in JUnit 【发布时间】:2016-01-14 02:21:28 【问题描述】:在不深入细节的情况下,我在一次运行我的 Junit 测试时遇到了问题。如果我逐个班级运行它们,一切都很棒!否则我会遇到麻烦,因为我无法在 junit-test-class 之间重新启动我的 WebApplication。这导致我的 WebApplication 中有 Zookeeper 服务器客户端,这些客户端在我关闭和启动 Zookeeper 服务器后在类之间徘徊。这些 Zookeeper 服务器客户端可能需要一段时间才能与服务器重新同步,这会导致不可预知的行为......
有没有办法通过调用 JUnit 测试的 @BeforeClass 和 @AfterClass 方法中的某些内容来重新启动我的 SpringBootServletInitializer 类?
WebApplication.java
@ComponentScan
@EnableAutoConfiguration
@EnableWebMvc
@EnableHyperMediaSupport(...)
@PropertySources(...)
public class WebApplication extends SpringBootServletInitializer
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder)
return builder.sources(WebApplication.class);
@Override
protected WebApplicationContext run(SpringApplication application)
application.getSources().remove(ErrorPageFilter.class);
return (WebApplicationContext) application.run();
public static void main(String[] args)
SpringApplication.run(WebApplication.class, args);
【问题讨论】:
也许@DirtiesContext
? docs.spring.io/spring/docs/current/javadoc-api/org/…
宾果游戏!请将您的评论变成答案,以便我检查:D
【参考方案1】:
您可以使用@DirtiesContext
注释。
这将提示 Spring Test 运行器重新加载测试方法之间的上下文。
【讨论】:
以上是关于我需要我的 Spring Boot Web 应用程序在 JUnit 中重新启动的主要内容,如果未能解决你的问题,请参考以下文章
Java/Spring Boot Web 应用程序。插入具有自动递增 id 列的新行
一次只有一个用户使用整个 Web 应用程序 - Spring Boot
具有 OAuth 2 和 JWT 安全性的 Spring Boot 微服务