Robert M.
Robert M.

Reputation: 1367

TestNG: Use ApplicationContext in multiple Test-Classes

I've written some test-cases inside a single TestNG Test which extends AbstractTestNGSpringContextTests. The ApplicationContext is correctly setup and I can use it inside my test-cases.

The problem is that the setting up of the applicationContext can take some time and I don't want to do this for every test-class I have, as this would take some time which is unnecessary from my point of view.

So my question is: Is it possible to run more than one TestNG test-class using the same Spring ApplicationContext which is setup only once?

Thanks and best regards, Robert

Upvotes: 0

Views: 2074

Answers (3)

Trinadh Sidda
Trinadh Sidda

Reputation: 69

Once the TestContext framework loads an ApplicationContext (or WebApplicationContext) for a test, that context will be cached and reused for all subsequent tests that declare the same unique context configuration within the same test suite.

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.

Upvotes: 1

Slava Semushin
Slava Semushin

Reputation: 15204

Spring may cache and re-use ApplicationContext when you use similar locations in @ContextConfiguration annotations. See related article from Tomasz Nurkiewicz (@tomasz-nurkiewicz) at http://nurkiewicz.blogspot.com/2010/12/speeding-up-spring-integration-tests.html

Upvotes: 1

Cedric Beust
Cedric Beust

Reputation: 15608

How about using a @BeforeSuite?

Upvotes: 1

Related Questions