How can I initialize a Spring applicationContext just once for all tests

筅森魡賤 提交于 2019-12-04 20:17:35

For fast test execution I want to make sure that the Spring context is initialized just once, then all the tests should be run against this context, then it should shut down.

I hate to ask the obvious, but...

Have you read the Testing chapter of the Spring Reference Manual?

Specifically, these sections explain what's going on:

Soooo, the TestContext framework certainly supports caching across tests within a test suite, and I should know, because I wrote it. ;)

Now as for why caching is not working for you, I can only assume that you have configured your build framework to fork for each test (or that you are running tests individually and manually within your IDE). Here's an excerpt from the last link above that might help you out:

Test suites and forked processes

The Spring TestContext framework stores application contexts in a static cache. This means that the context is literally stored in a static variable. In other words, if tests execute in separate processes the static cache will be cleared between each test execution, and this will effectively disable the caching mechanism.

To benefit from the caching mechanism, all tests must run within the same process or test suite. This can be achieved by executing all tests as a group within an IDE. Similarly, when executing tests with a build framework such as Ant, Maven, or Gradle it is important to make sure that the build framework does not fork between tests. For example, if the forkMode for the Maven Surefire plug-in is set to always or pertest, the TestContext framework will not be able to cache application contexts between test classes and the build process will run significantly slower as a result.

If you still experience issues after taking the above into consideration, please consider submitting a project that demonstrates your problem.

Cheers,

Sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!