Using @RunWith(SpringJUnit4ClassRunner.class), can you access the ApplicationContext object?
Solution 1
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...
}
Solution 2
Add an @Autowired attribute of ApplicationContext
@Autowired ApplicationContext applicationContext;
Solution 3
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")
egervari
Updated on June 25, 2022Comments
-
egervari about 2 years
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!