Where is the search getResourceAsStream ("file") when run from the test?

I am trying to create a test for validation ServletListenerthat loads a properties file. I tested when starting the application that it works fine and finds the file in classpath. But I do not know how to create a test for it. My idea is to create a temporary file with a test property and then verify that the property is placed in System properties. But I always can not create the file in the right place.

I tried to create a file in /target/test-classesor directly in the root directory of the application, but it never finds it. Any idea?

This is the code I'm trying to verify:

public class PropertyReadingListener implements ServletContextListener {

    public static final String PROFILES_PROPERTIES = "profiles.properties";

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        Properties propsFromFile = new Properties();
        try {
            propsFromFile.load(getClass().getResourceAsStream(PROFILES_PROPERTIES));
        } catch (final Exception e) {
            log.warn("Unable to find {}, using default profile", PROFILES_PROPERTIES);
        }
        propsFromFile.stringPropertyNames().stream()
            .filter(prop -> System.getProperty(prop) == null)
            .forEach(prop -> System.setProperty(prop, propsFromFile.getProperty(prop)));
    }
}

Thank.

+4
source share
3 answers

InputStream

, getClass(). getResourceAsStream, .. PropertyReadingListener com.company.listeners.PropertyReadingListener, com/company/listeners for .

, InputStream , convienent , InputStream, getResourceAsStream

0

getResourceAsStream ( "file" ) ?

, JUnit....

- , , , JVM .

(Junit 4 : . fooobar.com/questions/196234/...)


.

, , Java classpath classpath. , ( , JUnit runner ), , , .

+1

, maven, :

src/test/resources/foo.properties

maven (, )

target/test-classes/foo.properties

The catalog of test classes is located in the class path, so you refer to such a file (pay attention to the slash in front of the file name):

... getResourceAsStream("/foo.properties");
+1
source

Source: https://habr.com/ru/post/1654163/


All Articles