Java 如何使用 Spring 为 JUnit 测试注入 ServletContext?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2674697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inject ServletContext for JUnit tests with Spring?
提问by Juri Glass
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. But I don't know how to inject the ServletContext in my service class, so that I can test it with a JUnit test.
如果我在 Glassfish 上部署它,注入 ServletContext 并且它按预期工作。但是我不知道如何在我的服务类中注入 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。
采纳答案by Chris J
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 方法将此实例传递给您的服务对象。
回答by Adrian Duta
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;
}
});
}
回答by anre
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() {}
}