【问题标题】:RunWith and ContextConfiguration weird behaviourRunWith 和 ContextConfiguration 奇怪的行为
【发布时间】:2013-06-03 20:37:15
【问题描述】:

我有一个非常简单的课程:

 @RunWith(SpringJUnit4ClassRunner.class)
 @ContextConfiguration(locations={"classpath*:/application-context-this-does-not-exist.xml"})
  public class HTMLSourceExtractorImplTest {

    @Autowired
    ApplicationContext context;

    @Test
    public void test(){
         String [] beans = context.getBeanDefinitionNames();
             for(String bean : beans){
                 System.out.println(bean);
             }
         System.out.println("Testing");
    }
}

在类路径中指定的上下文文件不存在。我几乎可以输入任何我想要的名称,并且代码不会中断。我的意思是测试运行得很好,就好像那个文件真的存在一样。

如果我做一个小的改变,从 classpath* 到 classpath ,然后它会发出喙,说这个文件不存在,这是我所期望的行为在第一种情况下也是如此。

春季版本 3.2.3.RELEASE。

有人可以解释这种奇怪的行为吗?

编辑

建议的日志中的内容:

     20:47:26,923 INFO  [GenericApplicationContext] Refreshing org.springframework.context.support.GenericApplicationContext@3df6c65c: startup date [Fri Jun 07 20:47:26 PDT 2013]; root of context hierarchy

我什至尝试从应用程序上下文中输出所有 bean:

  org.springframework.context.annotation.internalConfigurationAnnotationProcessor
  org.springframework.context.annotation.internalAutowiredAnnotationProcessor
  org.springframework.context.annotation.internalRequiredAnnotationProcessor
  org.springframework.context.annotation.internalCommonAnnotationProcessor                   
  org.springframework.context.annotation.ConfigurationClassProcessor.importAwareProcessor

在我看来,如果是通配符,Spring 将创建一个默认的空应用程序上下文

【问题讨论】:

    标签: java spring unit-testing junit


    【解决方案1】:

    来自 JavaDoc 的引用可能会回答您的问题:

    /**
     * Pseudo URL prefix for all matching resources from the class path: "classpath*:"
     * This differs from ResourceLoader's classpath URL prefix in that it
     * retrieves all matching resources for a given name (e.g. "/beans.xml"),
     * for example in the root of all deployed JAR files.
     * @see org.springframework.core.io.ResourceLoader#CLASSPATH_URL_PREFIX
     */
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
    

    由于在您的类路径中没有与名称 application-context-this-does-not-exist.xml 匹配的 XML 文件,因此您的配置等于 @ContextConfiguration(locations={}) => 空应用程序上下文。

    但是当你使用CLASSPATH_URL_PREFIX = "classpath:" 时,这等于说“加载这个不存在的文件” => 错误加载上下文配置。

    【讨论】:

    • 老实说,我没有看到您提供的文档与创建的默认应用程序上下文之间有任何联系。很明显,确实创建了一个空上下文,但文档没有明确说明。谢谢你的回答。会支持这项工作,但我希望文档中有一个明显的声明。
    • 我已经描述过 - 没有要加载的 XML,剩下的只是一个空的上下文。
    • 你做到了,毫无疑问。但这从我运行的代码中很明显。没有冒犯,但对我来说,代码应该破解而不是传递。我稍后会接受这一点,除非我得到更好的解释。感谢您的宝贵时间!
    • 为什么会坏掉?因为它没有任何要加载的配置? classpath*: 是一个通配符前缀,它充当搜索过滤器,而不是确切的位置。
    • 我看不出你在哪里看到问题......那里没有问题。 SpringJUnit4ClassRunner aways 创建一个基本的应用程序上下文,然后将其与基于 @ContextConfiguration 注释参数加载的所有配置合并。您的参数导致没有配置被加载,因此上下文为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    • 2011-10-04
    • 2015-03-16
    • 2017-07-04
    相关资源
    最近更新 更多