简体   繁体   English

如何使用Spring为JUnit测试注入ServletContext?

[英]How to inject ServletContext for JUnit tests with Spring?

I want to unit test a RESTful interface written with Apache CXF. 我想对使用Apache CXF编写的RESTful接口进行单元测试。

I use a ServletContext to load some resources, so I have: 我使用ServletContext来加载一些资源,所以我有:

@Context
private ServletContext servletContext;

If I deploy this on Glassfish, the ServletContext is injected and it works like expected. 如果我在Glassfish上部署它,则会注入ServletContext并且它会按预期工作。 But I don't know how to inject the ServletContext in my service class, so that I can test it with a JUnit test. 但我不知道如何在我的服务类中注入ServletContext,以便我可以使用JUnit测试来测试它。

I use Spring 3.0, JUnit 4, CXF 2.2.3 and Maven. 我使用Spring 3.0,JUnit 4,CXF 2.2.3和Maven。

In your unit test, you are probably going to want to create an instance of a MockServletContext . 在单元测试中,您可能想要创建MockServletContext的实例。

You can then pass this instance to your service object through a setter method. 然后,您可以通过setter方法将此实例传递给服务对象。

As of Spring 4, @WebAppConfiguration annotation on unit test class should be sufficient, see Spring reference documentation 从Spring 4开始,单元测试类上的@WebAppConfiguration注释应该足够了,参见Spring参考文档

@ContextConfiguration
@WebAppConfiguration
public 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: 可能你想用servletContext.getResourceAsStream或类似的东西读取资源,为此我用Mockito这样:

 @BeforeClass
void 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;
        }
    });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM