2015-10-15 109 views
3

没有进入极端细节,我一次运行Junit测试时遇到了问题。如果我按班上课,一切都很好!否则我有麻烦,因为我无法在junit-test-class之间重新启动WebApplication。这使得我在我的WebApplication中拥有Zookeeper服务器客户端,这些客户端在我通过关闭和启动Zookeeper服务器之间的类之后停滞不前。这些Zookeeper服务器客户端可能需要一段时间才能与服务器重新同步,这会导致不可预知的行为...我需要我的Spring Boot WebApplication在JUnit中重新启动

有没有办法通过调用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); 
    } 
} 
+1

也许'@ DirtiesContext'? https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html –

+0

Bingo!请把你的评论变成答案,以便我可以检查它:D – smuggledPancakes

回答

4

你可以使用@DirtiesContext注解。

这将提示Spring Test runner在测试方法之间重新加载上下文。