如何通过代码以编程方式检索和修改@ConfigurationContext?通过代码以编程方式检索并修改@ConfigurationContext?
我有一个默认配置,它包含有效的xml文件。
现在我需要为特定的测试用例添加无效的配置并测试相同的配置。
如何通过代码以编程方式覆盖,检索和修改@ConfigurationContext?
由于提前, 本Kathir
如何通过代码以编程方式检索和修改@ConfigurationContext?通过代码以编程方式检索并修改@ConfigurationContext?
我有一个默认配置,它包含有效的xml文件。
现在我需要为特定的测试用例添加无效的配置并测试相同的配置。
如何通过代码以编程方式覆盖,检索和修改@ConfigurationContext?
由于提前, 本Kathir
免责声明:我假设你正在使用JUnit因为你没有在你的回复我的评论意见不同。
我认为你所要做的并不是很有意义,在我看来,为了能够做一个以上的测试,为你的非工作配置创建一个专门的测试类更好。但是:
@RunWith(SpringJUnit4ClassRunner.class)
和@ContextConfiguration(locations = {"classpath:/working-context.xml"})
注释您的测试类。通过这种方式,您可以通过两种方式检索配置上下文:首先,您可以简单地声明将包含工作上下文的字段@Inject ApplicationContext context
。或者,你让你的测试课implements ApplicationContextAware
,然后写一个public void setApplicationContext (ApplicationContext applicationContext)
。我会去第二个,因为它将以编程方式改变上下文。not-working-context.xml
并把它放在你的classpathcontext = setApplicationContext(new ClassPathXmlApplicationContext("not-working-context.xml"));
重新加载应用程序上下文和测试所有你喜欢的错误的测试方法。最终测试类的样子:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/working-context.xml"})
public class TestClass implements ApplicationContextAware {
private ApplicationContext context;
public void setApplicationContext(ApplicationContext context){
this.context = context;
}
//Other tests
@Test
public void zFailingTest() {
context = setApplicationContext(new ClassPathXmlApplicationContext("not-working-context.xml"));
//your test
}
}
当我加载无效的dozer mapping.xml,其中的类名称不正确,而不是加载成功,它会引发错误。引起:org.xml.sax.SAXParseException:cvc-elt.1:找不到元素的声明'映射。什么可能是错误的? Xml标题如下所示:<?xml version =“1.0”encoding =“UTF-8”?>
你试图(如果我猜错了,请纠正我)来测试Spring配置文件在缺少类,错别字等方面的错误时的行为。但是。基本上,Spring是一个在准备好使用之前会做很多工作(实例化,IoC等)的框架。你不能单元测试这种东西,因为所有的相关工作都是在环境提供给你之前完成的,所以所有的失败都会导致环境被关闭。开始阅读[this](http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/index.html) – ThanksForAllTheFish
是不是更容易,更好,如果你只需要创建一个新的上下文文件,然后用注释测试类'@ContextConfiguration( “classpath中:新的上下文file.xml”)'?至少在JUnit中是这样的 – ThanksForAllTheFish
但是它会使整个测试类都失败,我想通过测试用例并记录错误。我需要为此创建断言语句。 – Kathir