0

I am writing a unit test case like this,

 public class XMLUtilsTest {
  private static final String XML_FOR_TEST ="a/b/c/xml_utils_test.xml";


 @Before
 public void setup() {

 }

@Test
public void testGetElementValue() throws Exception {
  InputStream inputStream = readTestXML(XML_FOR_TEST);

  System.out.println("Input Stream: "+inputStream);
}

private InputStream readTestXML(String testXmlFile) {
//InputStream inputStream = XMLUtilsTest.class.getResourceAsStream(testXmlFile);
//InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(testXmlFile);
 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(testXmlFile);
 return inputStream;
 }
}

While debugging, i observe that this.getClass().getClassLoader() call in the readTestXML method loads class properly but when getResourceAsStream(testXmlFile) is invoked on output of this.getClass().getClassLoader() , the output is null.

my project structure is like this,

 --src
   --main
   --test
       --java
           --XMLUtilsTest.java
       --resources
           --a.b.c
               --xml_utils_test.xml

Please suggest.

Thanks,

Vijay Bhore

Here to Learn.
  • 677
  • 2
  • 10
  • 31

1 Answers1

2

Your code is working. All you need to do is to check if src/test/resources is on your classpath and you should be fine (Project properties -> java build path)

I just recreated your scenario and it worked fine.

//Both snippets should work (don't forget to prepend a slash if using getClass().getResourceAsStream)
System.out.println(this.getClass().getClassLoader().getResourceAsStream("a/b/c/file.txt"));
System.out.println(this.getClass().getResourceAsStream("/a/b/c/file.txt"));
Marlon Bernardes
  • 13,265
  • 7
  • 37
  • 44