Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text-file resource into Java unit test? [duplicate]

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?

like image 432
yegor256 Avatar asked Oct 08 '10 14:10

yegor256


People also ask

How do you read a resource file in JUnit?

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.

Where do you put test resources?

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.

How do unit tests work java?

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.


2 Answers

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();   } } 
like image 127
yegor256 Avatar answered Oct 25 '22 02:10

yegor256


Right to the point :

ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("file/test.xml").getFile()); 
like image 21
pablo.vix Avatar answered Oct 25 '22 01:10

pablo.vix