How to deal with relative path in Junits between Maven and Intellij

前端 未结 5 1628
臣服心动
臣服心动 2021-01-30 08:37

I have a maven project with a module

/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt

Consider a Junit in myModule

5条回答
  •  一向
    一向 (楼主)
    2021-01-30 09:13

    If you want to keep your code, you can try to change the working directory in the run/debug configuration (first entry in the combo box giving access to what you want to run) Set this to your module root. But prefer the other suggested approach:

    ClassLoader.getSystemResourceAsStream(youPath) 
    

    Or my preferred:

    getClass.getResource(youPath)
    

    or

    getClass.getResourceAsStream(youPath)
    

    A leading '/' in path indicates the working dir of your project, while no '/' indicates a relative dir to current class.

    I use this last solution for my tests: I put my test data resources at the same package level as the test source, or in a subdir to avoid too messy package.

    This way I can do a simple call without complicated path and without having to deal with working directory:

    project-root  
      - module A  
        - src  
          - test
            - rootfile.txt  
            - my-complicated-package-naming-root
              - mypackage
                - Test.java
                - testResource.xml  
    

    I can get the files this way:

    final URL rootfile= Test.class.getResource("/rootfile.txt");
    final URL testResource= Test.class.getResource("testResource.xml");
    

提交回复
热议问题