8

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

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

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

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"};
}

这会找到服务上下文,但其中定义的 PropertyPlaceholderConfigurer 无法找到它的属性文件。

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

6 回答 6

4

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

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

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

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

于 2009-06-18T17:54:04.897 回答
3

除了覆盖 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);
  }
于 2009-06-17T21:31:27.017 回答
1

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

于 2009-06-17T21:01:24.567 回答
1

你不能使用ClassPathXmlApplicationContext这样的类路径 XML 工厂吗?

于 2009-06-18T18:06:33.237 回答
0

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

于 2011-04-17T16:08:23.880 回答
0
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] { "WebRoot/WEB-INF/services-context.xml"})
于 2012-06-25T08:50:18.960 回答