How to inject ServletContext for JUnit tests with Spring? How to inject ServletContext for JUnit tests with Spring? spring spring

How to inject ServletContext for JUnit tests with Spring?


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.


As of Spring 4, @WebAppConfiguration annotation on unit test class should be sufficient, see Spring reference documentation

@ContextConfiguration@WebAppConfigurationpublic class WebAppTest {    @Test    public void testMe() {}}


Probably you want to read resources with servletContext.getResourceAsStream or something like that, for this I've used Mockito like this:

 @BeforeClassvoid setupContext() {    ctx = mock(ServletContext.class);    when(ctx.getResourceAsStream(anyString())).thenAnswer(new Answer<InputStream>() {        String path = MyTestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath()                + "../../src/main/webapp";        @Override        public InputStream answer(InvocationOnMock invocation) throws Throwable {            Object[] args = invocation.getArguments();            String relativePath = (String) args[0];            InputStream is = new FileInputStream(path + relativePath);            return is;        }    });}