Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @RunWith(SpringJUnit4ClassRunner.class), can you access the ApplicationContext object?

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!

like image 804
egervari Avatar asked Feb 11 '13 23:02

egervari


People also ask

How can you access the application context in Spring integration test?

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 .

What is @RunWith SpringJUnit4ClassRunner class )?

@RunWith(SpringJUnit4ClassRunner. class): Indicates that the class should use Spring's JUnit facilities.

Which annotation will set ApplicationContext for the test class?

Set the spring ApplicationContext for your test classes using @ContextConfiguration annotation.

What is the use of @RunWith SpringRunner class?

@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.


1 Answers

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...
}
like image 59
Mark Avatar answered Oct 19 '22 13:10

Mark