Java – loading a resource file in unit test code

    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;
    }
Advertisements
This entry was posted in Java, Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s