RunWith和ContextConfiguration很奇怪的行为

Eug*_*ene 8 java junit spring unit-testing

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

 @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");
    }
}
Run Code Online (Sandbox Code Playgroud)

在类路径中指定的此上下文文件不存在.我几乎可以放任何我想要的名字,但代码不会破坏.我的意思是测试运行得很好,好像该文件确实存在.

如果我做一个小的改动,从:classpath*classpath,那么它就是beaks,说这个文件不存在,这也是我在第一种情况下所期望的行为.

Spring Version 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
Run Code Online (Sandbox Code Playgroud)

我甚至尝试从应用程序上下文输出所有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
Run Code Online (Sandbox Code Playgroud)

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

Pav*_*ral 18

来自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*:";
Run Code Online (Sandbox Code Playgroud)

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

但是,当您使用时CLASSPATH_URL_PREFIX = "classpath:",这等于说"加载此不存在的文件" => 错误加载上下文配置.

  • 我看不出你在哪里看到这个问题......那里没有问题.`SpringJUnit4ClassRunner` aways创建一个基本的应用程序上下文,然后将其与基于`@ContextConfiguration`注释参数加载的所有配置合并.您的参数导致没有加载配置,因此导致空上下文. (3认同)
  • 为什么它应该破裂?因为它没有任何配置要加载?`classpath*:` 是一个通配符前缀,充当搜索过滤器,而不是确切位置。 (2认同)