I need my Spring Boot WebApplication to restart in JUnit
Asked Answered
V

1

10

Without going into excruciating detail, I am having an issue when I run my Junit tests all at once. If I run them class by class, everything is great! Otherwise I have trouble because I cannot restart my WebApplication inbetween junit-test-class. This causes me to have Zookeeper server clients in my WebApplication that hang around after I go through the shutdown and startup of the Zookeeper server in-between classes. Those Zookeeper server clients can take a while to resync with server and this causes unpredictable behavior...

Is there a way to have my SpringBootServletInitializer class restart by calling something in the @BeforeClass and @AfterClass methods of a JUnit test?

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);
    }
}
Vlf answered 15/10, 2015 at 14:49 Comment(2)
Maybe @DirtiesContext ? docs.spring.io/spring/docs/current/javadoc-api/org/…Lula
Bingo! Please turn your comment into answer so I can check it :DVlf
L
10

You could use the @DirtiesContext annotation.

This will hint to the Spring Test runner to reload the context between test methods.

Linneman answered 16/10, 2015 at 8:20 Comment(1)
Remember to use it on the test that "soils" the application context, which is not necessarily the one that fails due to a soiled (by other tests) application context.Shunt

© 2022 - 2024 — McMap. All rights reserved.