我有一个跨多个Spring bean定义xml文件的大型应用程序。在我的测试套件中,我使用FileSystemXmlApplicationContext手动加载我需要的XML文件,以执行我想要运行的测试。这减少了测试设置时间,并允许我使用生产中使用的完全相同的配置文件。

现在我正在尝试使用Spring的事务测试基类,它接受配置位置并为我加载上下文。出于某种原因,当创建应用程序上下文时,Spring无法找到任何配置文件。这很令人困惑,因为我从同一个工作目录运行测试,就像我自己使用FileSystemXmlApplicationContext加载配置一样。如果我在我的所有配置位置前加上“file:”找到我在测试中指定的路径,但找不到配置中定义的bean(例如属性文件)导入或引用的任何文件。这是怎么回事?我是否可以获得扩展spring上下文测试类的测试,使其与我自己创建上下文的测试相同?

例如,创建像这样的上下文可以正常工作:

ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "WEB-INF/services-context.xml"})

如果我扩展AbstractTransactionalDataSourceSpringContextTests,则以下找不到services-context.xml:

@Override
protected String[] getConfigLocations() {
   return new String[] { "WEB-INF/services-context.xml"};
}

这可以找到services-context,但是在那里定义的PropertyPlaceholderConfigurer无法找到它的属性文件。

 @Override
 protected String[] getConfigLocations() {
    return new String[] { "file:WEB-INF/services-context.xml"};
 }
有帮助吗?

解决方案 2

除了覆盖getConfigLocations之外,我还覆盖了loadContext并在那里使用了可靠的fileSystemXmlApplicationContext。

 @Override
 protected String[] getConfigLocations() {
     return new String[] { "WEB-INF/services-config.xml" };
 }

 @Override
 protected ConfigurableApplicationContext loadContext(String[] locations) throws Exception {
     return new FileSystemXmlApplicationContext(locations);
  }

其他提示

我们将所有Spring配置和属性文件放在类路径中,这使事情变得简单 - 我们可以从基类扩展我们的测试类,如:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={
        "/spring/*.xml", 
        "/testSpring/*.xml" })
public abstract class AbstractIntegrationTest  {

这里,路径是类路径中的所有路径。

如果您不想这样做,您是否检查过如何引用services-context.xml中的属性文件?我怀疑如果你将file:添加到你的上下文配置中,那么你还需要将它添加到你的属性文件引用中。您可以使用单独的测试Spring配置文件来更改属性占位符的定义,并将其放在上下文文件列表的末尾 - 然后它的定义将覆盖早期文件中定义的那些。

您的配置位置是相对URI,并且将由基本测试类解释,其中URI相对于测试类本身的位置进行解析。尝试使用完全限定的URI,或使用相对URI考虑测试类的位置。

你不能使用像 ClassPathXmlApplicationContext

另一种可能的解决方案是复制 services-config.xml 并重命名为 services-config-test.xml ,然后放在classpath下。属性文件也是如此。

ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "WebRoot/WEB-INF/services-context.xml"})
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top