Reputation: 22522
I have a Spring test that uses:
@RunWith(SpringJUnit4ClassRunner.class)
Unlike the older way of testing, extending from the Spring test base classes, there appears to be no obvious way to access to the ApplicationContext that has been loaded by Spring using @ContextConfiguration
How can I access the ApplicationContext
object from my test methods?
Thanks!
Upvotes: 12
Views: 20655
Reputation: 1761
I use this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class MyClassTest
{
}
and go to project build path -> Source ->
add the location of your applicationContext.xml
I use maven so the applicationContext.xml
is under src/main/resources
.
If you use this method you can have a multiple applicationContext for testing for example :
@ContextConfiguration("classpath:applicationContext_Test.xml")
or
@ContextConfiguration("classpath:applicationContext_V01.xml")
Upvotes: 3
Reputation: 29139
From the Integration Testing section of the Spring Documentation
@Autowired ApplicationContext
As an alternative to implementing the ApplicationContextAware interface, you can inject the application context for your test class through the @Autowired annotation on either a field or setter method. For example:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {
@Autowired
private ApplicationContext applicationContext;
// class body...
}
Upvotes: 14
Reputation: 9777
Add an @Autowired attribute of ApplicationContext
@Autowired ApplicationContext applicationContext;
Upvotes: 3