简体   繁体   English

Java单元测试期间的类路径

[英]Class Path during unit testing in java

I have a file in /src/main/java which has the following line of code : 我在/ src / main / java中有一个文件,其中包含以下代码行:

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.. 并且相应的资源文件位于/ src / main / resources中...但是我们正在考虑从classpath(src / main / resources)文件夹中删除此test.json,我们将再添加一个jar依赖项,该jar将包含这个test.json ...通过将这个文件放在src / test / resources文件中,是否可以运行测试用例。

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 项目:newfile

Files: 档案:

Test.java Test.java

package newfile.org;

public class Test {

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

    }

}

myfile.txt myfile.txt

It's my file

Set as jar library to other project: 设置为其他项目的jar库:

MyClass.java 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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