Why Can't I access src/test/resources in Junit

2019-03-08 13:17发布

I am having a problems running the following code:

configService.setMainConfig("src/test/resources/MainConfig.xml");

From within a Junit @Before method.

Is this the way Maven builds out its target folder?

2条回答
姐就是有狂的资本
2楼-- · 2019-03-08 13:42

Access MainConfig.xml directly. The src/test/resources directory contents are placed in the root of your CLASSPATH.

More precisely: contents of src/test/resources are copied into target/test-classes, so if you have the following project structure:

.
└── src
    └── test
        ├── java
        │   └── foo
        │       └── C.java
        └── resources
            ├── a.xml
            └── foo
                └── b.xml

It will result with the following test CLASSPATH contents:

  • /foo/C.class
  • /a.xml
  • /foo/b.xml

To actually access the files from Java source, use getClass().getResource("/MainConfig.xml").getFile().

查看更多
别忘想泡老子
3楼-- · 2019-03-08 13:53

I guess setMainConfig expects the path of a resource, that it will load using the ClassLoader, and not a relative file path. It would help if you linked to the javadoc of this mysterious configService.setMainConfig method.

If my guess is correct, then the path should just be MainConfig.xml. Mave copies the contents of src/test/resources to the target/test-classes (IIRC) folder. And this test-classes folder is in the classpath of the unit tests.

查看更多
登录 后发表回答