Java - loading a resource file in unit test code

less than 1 minute read

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    String xml = getResourceString("/test_files/TestProperties.xml");
    private String getResourceString(String resourcePath) {
        InputStream inputStream = null;
        try {
            URL url = getClass().getResource(resourcePath);
            File file = new File(url.toURI());
            boolean exist = file.exists();
            org.junit.Assert.assertTrue(exist);
            inputStream = this.getClass().getResourceAsStream(resourcePath);
            String xmlResult = IOUtils.toString(inputStream, "UTF-8");
            return xmlResult;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception ex) {
                logger.error(ex.getMessage(), ex);
            }
        }
        return null;
    }