小编典典
我最终使用Spring
MockServletContext类,并在测试运行之前将其直接注入到我的服务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:..//src/main/webapp");
myService.setServletContext(mockServletContext);
}
如果我有多个使用Servlet
Context的类,那么更好的解决方案是使用WebApplicationContext代替默认的类(当前由DelegatingSmartContextLoader提供),但是它将需要实现自定义ContextLoader类并将其类名传递给
@ContextConfiguration 批注。
*后来想到的*另一种更清洁的解决方案 是重构服务并ServletContext
通过@Autowired而不是进行注入ServletContextAware,并提供相应类型的bean(实际上是一个MockServletContext实例)。
将来可能MockServletContext会在Spring中添加来自测试类的直接支持,请参阅SPR-5399和SPR-5243。
*春季3.2的*更新 在Spring
3.2中,Servlet上下文的初始化变得像添加一个@WebAppConfiguration注释一样简单:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("file:..//src/main/webapp")
@ContextConfiguration(locations = { "/test-ctx.xml" } )
public class SomeServiceTest {
查看文章中的详细信息
2020-11-23