javaunit-testing

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


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?


Solution

  • 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();
      }
    }