我正在尝试在spring mvc应用程序中为控制器编写集成测试.控制器调用服务类,服务类又调用dao从存储库读取/写入数据.DAO需要查找一些配置.配置bean在WEB-INF/applicationContext.xml中定义.
我正在使用这样的东西:
配置config =(配置)ContextLoader.getCurrentWebApplicationContext().getBean("config");
private String namespace = config.getProperty("someproperty");
属性存储在zookeeper中,所以我没有使用spring的属性管理工件.
问题是在运行JUnit测试时,ContextLoader.getCurrentWebApplicationContext()始终返回null.
我迄今看着下面的方法:
1,特德年轻的做法(只是谷歌搜索的Spring MVC集成测试特德青年)
2. https://github.com/SpringSource/spring-test-mvc
3.本网站..问题/ 8464919/unit-testing-a-servlet -s-depends-on-springs-webapplicationcontextutils-getre
4.使用Selenium/JWebunit
5. http://confluence.highsource.org/display/Hifaces20/Hifaces20+Testing+package+ - +测试%2C +跟踪+和+调试+幅+与+码头应用+
1无法解决此问题.WebApplicationContext保持null
2状态,支持WebApplicationContext将在Spring 3.2中提供
3.我不明白这一点.我从哪里获取testApplicationContext和getServletContext()?
我不想这样,因为这是完全黑盒测试.
5.我目前正在查看5.但这需要启动一个servlet容器.没有其他选择吗?
我将非常感谢您提供的任何帮助.
感谢PixalSoft
@Ted Young SO不允许我完成我的说法.使用loader = MockWebApplicationContextLoader,它是不是应该作为默认的上下文加载器完全可用,因为当servappcontainer初始化webapp时Spring ContextLoader的行为?是吗?我需要做些什么来获取MockWebApplicationContextLoader的句柄?注入配置对象适用于单例对象.但一切都不能单身.在每个构造函数中传递配置对象听起来太单调乏味.现在,我创建了一个具有静态配置对象的类,通过setter方法自动装配.我将看一下ApplicationContextAware.Many thx
小智 5
您必须手动将 WebApplication 上下文添加到 ContextLoderListner。这将起作用。
@ContextConfiguration(locations = "classpath:module-test-beans.xml")
@WebAppConfiguration
public class SampleTest extends AbstractTestNGSpringContextTests {
@Autowired
private WebApplicationContext wac;
@BeforeClass
public void setUp() throws ServletException {
MockServletContext sc = new MockServletContext("");
ServletContextListener listener = new ContextLoaderListener(wac);
ServletContextEvent event = new ServletContextEvent(sc);
listener.contextInitialized(event);
}
@Test
public void testMe() {
Assert.assertFalse(ContextLoader.getCurrentWebApplicationContext() == null);
}
}
Run Code Online (Sandbox Code Playgroud)
将属性文件存储在类路径中。
现在在控制器类中访问该属性,如下所示:
/*to access your filename.properties file */
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));
String sServerLocation = properties.getProperty("key");
Run Code Online (Sandbox Code Playgroud)
现在您可以访问您的属性文件。
我确信它会起作用。
| 归档时间: |
|
| 查看次数: |
4265 次 |
| 最近记录: |