我最终使用SpringMockServletContext类,并在测试运行之前将其直接注入到我的服务bean中,因为我的服务已实现ServletContextAware
:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/test-ctx.xml" } )
public class SomeServiceTest {
@Autowired
private MyServletContextAwareService myService;
@Before
public void before(){
//notice that I had to use relative path because the file is not available in the test project
MockServletContext mockServletContext = new MockServletContext("file:../<my web project name>/src/main/webapp");
myService.setServletContext(mockServletContext);
}
如果我有多个使用Servlet Context的类,那么更好的解决方案是使用WebApplicationContext代替默认的类(当前由DelegatingSmartContextLoader提供),但是它将需要实现自定义ContextLoader类并将其类名传递给 批注。
是重构服务并ServletContext
通过@Autowired
而不是进行注入ServletContextAware
,并提供相应类型的bean(实际上是一个MockServletContext
实例)。
将来可能
MockServletContext
会在Spring中
添加来自测试类的直接
支持,请参阅
SPR-5399和
SPR-5243。
在Spring 3.2中,Servlet上下文的初始化变得像添加一个@WebAppConfiguration
注释一样简单:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("file:../<my web project name>/src/main/webapp")
@ContextConfiguration(locations = { "/test-ctx.xml" } )
public class SomeServiceTest {
查看文章中的详细信息