Dennis Thrysøe
Dennis Thrysøe

Reputation: 1911

Junit testing started spring context

I have a junit test case that instantiates and configures a spring context with @RunWith(SpringJUnit4ClassRunner.class)

In this spring context I have beans implementing the Lifecycle interface.

How do I "start" the spring context before the tests are invoked and stop it again afterwards?

Upvotes: 2

Views: 1033

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

@RunWith(SpringJUnit4ClassRunner.class) over class named MyTestCase is enough. Spring test framework will look for MyTestCase-test.xml file on the CLASSPATH. If you don't like this naming convention, you can specify your own one:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
public class MyTestCase {

  @Autowired
  private Dependency dep;

}

How do I "start" the spring context before the tests are invoked and stop it again afterwards?

Typically you don't have to do anything. Spring will start application context before the first test and shut it down automatically when JVM running the tests closes. Also you can restart context after each test (see @DirtiesContext annotation).

Upvotes: 0

NimChimpsky
NimChimpsky

Reputation: 47290

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext-TEST.xml")
public class MyIntegrationTest {}

then just reference beans as you normally would

Upvotes: 3

Related Questions