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!
By default the ApplicationContext is loaded using the GenericXmlContextLoader which loads a context from XML Spring configuration files. You can then access beans from the ApplicationContext by annotating fields in your test class with @Autowired , @Resource , or @Inject .
@RunWith(SpringJUnit4ClassRunner. class): Indicates that the class should use Spring's JUnit facilities.
Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.
@RunWith(SpringRunner. class) provides a bridge between Spring Boot test features and JUnit. Whenever we are using any Spring Boot testing features in our JUnit tests, this annotation will be required.
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...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With