Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject ServletContext for JUnit tests with Spring?

I want to unit test a RESTful interface written with Apache CXF.

I use a ServletContext to load some resources, so I have:

@Context
private ServletContext servletContext;

If I deploy this on Glassfish, the ServletContext is injected and it works like expected. But I don't know how to inject the ServletContext in my service class, so that I can test it with a JUnit test.

I use Spring 3.0, JUnit 4, CXF 2.2.3 and Maven.

like image 389
Juri Glass Avatar asked Apr 20 '10 11:04

Juri Glass


People also ask

What annotation causes JUnit to let spring boot control the test?

Spring Boot provides a @SpringBootTest annotation, which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests through SpringApplication .

Which annotation is provided to load a spring container in application JUnit test?

We do this using JUnit's @RunWith annotation. We also annotate our test class with Spring's @ContextConfiguration annotation without specifying any attributes.


1 Answers

In your unit test, you are probably going to want to create an instance of a MockServletContext.

You can then pass this instance to your service object through a setter method.

like image 193
Chris J Avatar answered Oct 17 '22 05:10

Chris J