Reset Spring-Boot During Integration Tests

2019-05-19 23:22发布

问题:

I guess am trying to get a corner case to work here. In my current project there are about 20 integration tests. One new integration test requires @EnableAsync to make the test work:

@RunWith(SpringRunner.class)
@EnableAsync
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
public class MyITest {
  :
}

When run alone, this test works fine.

Considering Maven and Eclipse' execution of tests in one project and knowing that the environment is only created once and reused (or soft-reset) for all integration tests, it's somewhat a requirement that this integration test runs first. However, that's (nearly?) never the case.

Therefore, this integration test (nearly?) always fails. One obvious solution is to add @EnableAsync to all integration tests. However, that's a bad dependency which I bet is broken once somebody adds another integration test and forgets this requirement.

I'm looking for a way to force the SpringRunner to completely reset the context and really start it from scratch also looking at @EnableAsync. Ideally that way includes to flag that SpringRunner has to reset the context (i.e., remove the @EnableAsync) after the test, too. That way any order of execution would ensure that only that very one test has the @EnableAsync.

Is there a way to do this? Or can I manually turn on/off the async-stuff by code in a @Before/@After method?

回答1:

take a look at DirtiesContext

Not sure if this is what you're looking for.

Possible duplicate of: How do you reset Spring JUnit application context after a test class dirties it?



回答2:

Whow, I think I just found out by accident... What I have now:

@RunWith(SpringRunner.class)
@EnableAsync
@SpringBootTest(webEnvironment = WebEnvironment.NONE, classes = {
    ClassWithAnAutowiredAsyncDependency.class // <=== difference!!! ===>
})
public class MyITest {
:
  @Autowired
  private ClassWithAnAutowiredAsyncDependency mine;
:
}

It seems as if the given classes are reset (specially?) or at least the autowiring happens in there again or something. I can't explain it any different.

I'm sure that this integration test is not the first integration test being run and still the asynchronous bit seems to be in place.

Well, test is green, it works...