如何处理Maven和Intellij之间Junits的相对路径 [英] How to deal with relative path in Junits between Maven and Intellij

查看:166
本文介绍了如何处理Maven和Intellij之间Junits的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带模块的maven项目

I have a maven project with a module

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

考虑 myModule 中的一个Junit需要打开 bar.txt ,maven的basedir是模块目录。

Consider a Junit in myModule which needs to open bar.txt, with maven the basedir is the module directory.

所以打开文件 bar.txt

  new File("foo/bar.txt")

当你执行 mvn test 但是当您在 intellij 中启动相同的junit时,它会失败,因为Intellij在项目目录中设置了basedir,而不是模块目录。

This works well when you execute mvn test BUT when you launch the same junit in intellij, it fails because Intellij sets the basedir in the project directory, not the module directory.

Intellij尝试打开 myProject / foo / bar.txt 而不是 myProject / myModule /foo/bar.txt

Intellij tries to open myProject/foo/bar.txt instead of myProject/myModule/foo/bar.txt

有没有办法解决这个问题?

Is there a way to deal with that ?

推荐答案

如果要保留代码,可以尝试更改运行/调试配置中的工作目录(组合框中的第一个条目可以访问您要运行的内容)
将此项设置为模块根目录。
但更喜欢其他建议的方法:

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) 

或者我的首选:

getClass.getResource(youPath)

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  

我可以获取文件这样:

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

这篇关于如何处理Maven和Intellij之间Junits的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆