Is it possble to reset Spring-Test's context cache before a test suite runs (not after)

7.5k Views Asked by At

We use spring-test (4.x) with junit. Is it possible to reset spring-test's context cache before a test suite runs (not after).

@DirtiesContext only seems to have options to reset the context after execution. We'd like a way to signal spring-test that a specific test suite should be run with a fresh non-cached context (so that we can easily override bean definitions in our tests). Whether this is an extension to @DirtiesContext or a new annotation such as @RunWithFreshContext doesn't matter as long as we can do so :-)

1

There are 1 best solutions below

5
On BEST ANSWER

UPDATE:

As of Spring Framework 4.2, it will be possible to use @DirtiesContext to close a test ApplicationContext before a test class or test method. See JIRA issue SPR-12429 for details.


No, as of Spring Framework 4.1.2, it is not currently possible to have the Spring TestContext Framework remove an ApplicationContext from the cache before the execution of a test method or test class.

However, it is possible to develop your own custom TestExecutionListener that does this for you. For example, you could extend DirtiesContextTestExecutionListener and execute its dirtyContext(...) method in the beforeTestClass(...) and beforeTestMethod(...) methods as you see fit. Naturally, if you include your custom TestExecutionListener alongside DirtiesContextTestExecutionListener, you wouldn't want your custom listener to perform the same actions of afterTestMethod(...) and afterTestClass(...) from DirtiesContextTestExecutionListener. So you might opt to override those two methods with no-ops or alternatively forgo declaration of the DirtiesContextTestExecutionListener in favor of your custom extension.

Regards,

Sam (component lead for spring-test)