如何使用Spring为JUnit测试注入ServletContext? [英] How to inject ServletContext for JUnit tests with Spring?

查看:110
本文介绍了如何使用Spring为JUnit测试注入ServletContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对使用Apache CXF编写的RESTful接口进行单元测试。

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

我使用ServletContext加载一些资源,所以我有:

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

@Context
private ServletContext servletContext;

如果我在Glassfish上部署它,则会注入ServletContext,它的工作方式与预期的一样。但我不知道如何在我的服务类中注入ServletContext,以便我可以使用JUnit测试来测试它。

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.

我使用Spring 3.0,JUnit 4,CXF 2.2.3和Maven。

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

推荐答案

在你的单元测试中,你可能想要创建一个 MockServletContext

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

然后,您可以通过setter将此实例传递给服务对象方法。

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

这篇关于如何使用Spring为JUnit测试注入ServletContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆