简体   繁体   中英

Why does Spring's @ContextConfiguration run when given a nonexistent file?

I'm debugging someone's java and trying to figure out whether spring config files are being properly loaded. This is complicated by the fact that it seems that Spring silently ignores nonexistent files. For example, the following runs just fine:

import org.springframework.test.context.*;
import org.junit.runner.*;
import org.junit.Test;
import org.springframework.test.context.junit4.*;

@ContextConfiguration(locations={"classpath:I_DONT_EXIST.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class Test3 {
    public static void main(String [] args){
        System.out.println("Hello World");
    }

    @Test
    public void testSomething() {
    }
}

Despite the fact that the indicated file I_DONT_EXIST.xml does not exist anywhere. Is there a way to modify it so if the indicated file doesn't exist, the runtime will complain?

Spring will complain about missing context xml files.

I'm not sure how you are using the class you pasted but in order to startup spring context for a test (having it executed on JUnit framework) you could annotate your class as follows:

@ContextConfiguration(locations={"classpath:I_DONT_EXIST.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
public class Test2 {
    public static void main(String [] args){
        System.out.println("Hello World");
    }

    @Test
    public void testSomething() {
    }
}

This will throw the following exception when tried to execute as JUnit test:

Caused by: java.io.FileNotFoundException: class path resource [I_DONT_EXIST.xml] cannot be opened because it does not exist
    at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157) ~[org.springframework.core-3.2.4.RELEASE.jar:3.2.4.RELEASE]
    at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ~[org.springframework.beans-3.2.4.RELEASE.jar:3.2.4.RELEASE]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM