Junit + getResourceAsStream Returning Null

后端 未结 13 1349
情话喂你
情话喂你 2020-12-15 03:32

Not sure how this is possible. I re-read up on getResourceAsStream and it\'s always returning null.

InputStream source = this.getClass().getResourceAsStream(         


        
相关标签:
13条回答
  • 2020-12-15 03:32

    Assuming test.xml is located right under your test root source folder, do this:-

    InputStream source = this.getClass().getClassLoader().getResourceAsStream("test.xml");
    
    0 讨论(0)
  • 2020-12-15 03:33

    Try MyClass.getResourceAsStream().

    Also try putting the test.xml in your classpath. For instance, in an Eclipse web project put text.xml in webcontent/WEB-INF/classes

    0 讨论(0)
  • 2020-12-15 03:34

    Add the folder that your having your resource files in to the source folders of eclipse. Then the file should be automatically put in the bin directory.

    0 讨论(0)
  • 2020-12-15 03:37

    In case you are using Maven, add this part to your pom.xml

    <build>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
    </build>
    

    Your test.xml and other resource files must be located in src/test/resources

    0 讨论(0)
  • 2020-12-15 03:37

    I always have problem with this method. Here are 2 links, which might be useful:

    • Describes diference between getClass().getResource(); and getClass().getClassLoader().getResource();
    • Simple utility which simplifies these 2 approaches

    I always experiment with adding "/" at the beginning or "./".

    From my experience the best method is using FileInputStream. There is only one thing to remember (while using FileInputStream with Eclipse), with default settings, your working directory is set to projects root. You can always check where is your current directory (and what relative paths you need)using this piece of code.

    0 讨论(0)
  • 2020-12-15 03:38

    It's not finding the resource on the classpath. If you are using junit and maven make sure the resources are copied on the target/test-classes by adding <include> file directive on <testResource> section

    You can also find out the location of your class in the file system by using

    this.getClass().getResource(".")
    

    and checking to see if the resource is there

    0 讨论(0)
提交回复
热议问题