简体   繁体   中英

Class Path during unit testing in java

I have a file in /src/main/java which has the following line of code :

Test.class.getClassLoader().getResourceAsStream("test.json")

and the corresponding resource file is present in /src/main/resources...But we are thinking to remove this test.json from the classpath (src/main/resources) folder and we would include one more jar dependency and that jar would contain this test.json...I have tested with jar dependency and its working fine as it will be in the classPath..But the problem is we have some test cases ..these will fail if we dont include the jar dependency...Is it possible to run the test cases by putting this file in src/test/resources file..Without giving the jar dependencies..

Try this, I am not sure but it should work:

URL fileUrl = Test.class.getResource("test.json");
File testFile= new File(FileLocator.toFileURL(fileUrl).getPath());

See this one.

different-ways-of-loading-a-file-as-an-inputstream

This one work for me:

Project: newfile

Files:

Test.java

package newfile.org;

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

myfile.txt

It's my file

Set as jar library to other project:

MyClass.java

    package example;

    import newfile.org.Test;

public class MyClass {

     public static void main(String args[]) {

        try (
                InputStream resourceAsStream = Test.class.getResourceAsStream("myfile.txt")) {
                if(resourceAsStream == null) {
                    System.out.println("it's null");
                }
                int r;
                while((r = resourceAsStream.read()) != -1) {
                    System.out.println((char)r);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

Output:

I
t
'
s

m
y

f
i
l
e

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM