tbr*_*lle 44 java junit maven-2 intellij-idea
我有一个带模块的maven项目
/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt
Run Code Online (Sandbox Code Playgroud)
考虑myModule中需要打开bar.txt的Junit ,使用maven,basedir是模块目录.
所以要打开文件bar.txt :
  new File("foo/bar.txt")
Run Code Online (Sandbox Code Playgroud)
当你在intellij中启动相同的junit 时执行mvn test BUT时,这很有效,因为Intellij在项目目录中设置了basedir,而不是模块目录.
Intellij尝试打开myProject/foo/bar.txt而不是myProject/myModule/foo/bar.txt
有办法解决这个问题吗?
tbr*_*lle 84
受Guillaume启发的解决方案:
在Run->Edit configuration->Defaults->JUnit->Working directoryset中,值$MODULE_DIR$和Intellij将像Maven一样设置所有junits中的相对路径.
Gui*_*ume 25
如果要保留代码,可以尝试更改运行/调试配置中的工作目录(组合框中的第一个条目可以访问您要运行的内容)将此设置为模块根目录.但更喜欢其他建议的方法:
ClassLoader.getSystemResourceAsStream(youPath) 
Run Code Online (Sandbox Code Playgroud)
或者我的首选:
getClass.getResource(youPath)
Run Code Online (Sandbox Code Playgroud)
要么
getClass.getResourceAsStream(youPath)
Run Code Online (Sandbox Code Playgroud)
路径中的前导'/'表示项目的工作目录,而没有'/'表示当前类的相对目录.
我将最后一个解决方案用于我的测试:我将测试数据资源放在与测试源相同的包级别,或者放在子目录中以避免太乱的包.
这样我就可以在没有复杂路径的情况下进行简单的调用,而无需处理工作目录:
project-root  
  - module A  
    - src  
      - test
        - rootfile.txt  
        - my-complicated-package-naming-root
          - mypackage
            - Test.java
            - testResource.xml  
Run Code Online (Sandbox Code Playgroud)
我可以这样得到文件:
final URL rootfile= Test.class.getResource("/rootfile.txt");
final URL testResource= Test.class.getResource("testResource.xml");
Run Code Online (Sandbox Code Playgroud)
        Sea*_*oyd 12
a)不要使用Files,请使用InputStreams.得到你的InputStream通过
ClassLoader.getSystemResourceAsStream("foo/bar.xml")
Run Code Online (Sandbox Code Playgroud)
大多数处理文件的API也对InputStreams感到满意.
b)不要使用foo目录,使用maven和IDE知道的目录(即将它们放入src/main/resources或src/test/resources,因此它们在类路径上)
c)如果你有一个绝对需要a的API File,而不是a InputStream,你仍然可以
new File(ClassLoader.getSystemResource("foo/bar.xml").toURI())
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           36982 次  |  
        
|   最近记录:  |