I have a unit test that needs to work with XML file located in src/test/resources/abc.xml
. What is the easiest way just to get the content of the file into String
?
File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file. getAbsolutePath(); System. out.
what is a resource? a resource is a file in the class path folder structure for your project. this is important because your test resources will be put in your test-classes folder hierarchy and your main resources will be put in your classes folder hierarchy — both in your target folder.
Unit testing refers to the testing of individual components in the source code, such as classes and their provided methods. The writing of tests reveals whether each class and method observes or deviates from the guideline of each method and class having a single, clear responsibility.
Finally I found a neat solution, thanks to Apache Commons:
package com.example; import org.apache.commons.io.IOUtils; public class FooTest { @Test public void shouldWork() throws Exception { String xml = IOUtils.toString( this.getClass().getResourceAsStream("abc.xml"), "UTF-8" ); } }
Works perfectly. File src/test/resources/com/example/abc.xml
is loaded (I'm using Maven).
If you replace "abc.xml"
with, say, "/foo/test.xml"
, this resource will be loaded: src/test/resources/foo/test.xml
You can also use Cactoos:
package com.example; import org.cactoos.io.ResourceOf; import org.cactoos.io.TextOf; public class FooTest { @Test public void shouldWork() throws Exception { String xml = new TextOf( new ResourceOf("/com/example/abc.xml") // absolute path always! ).asString(); } }
Right to the point :
ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("file/test.xml").getFile());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With