java暴露方法,将私有Java9模块的包暴露给JUnit的正确方法是什么?

I have an "executable" Java 9 module (meaning it won't expose any packages, it just contains a main function) which I need to test.

I am using Gradle's java-library and org.gradle.java.experimental-jigsaw plugins.

I have some package-private methods I need to test, and when I run in IntelliJ the tests work, but when running with Gradle, I get many errors like this:

abc.MyClassTest > myTestMethod FAILED

java.lang.IllegalAccessException

In the Gradle report, I see the root of the error:

class org.junit.runners.BlockJUnit4ClassRunner (in module junit)

cannot access class abc.MyClassTest (in module com.my.mod)

because module com.my.mod does not export abc to module junit

If I add this to my module-info.java file, it works with a warning:

exports abc to junit; // I don't really want to export this

Warning (when compiling):

warning: [module] module not found: junit

This looks pretty horrible even without the warning, in my opinion.

My question: how to "open" this package for tests only to avoid warnings and errors?

解决方案

As the Gradle Plugin is still experimental (6 months after the release of Java 9), it seems it still has some bugs and missing features.

But here's how to work around the issue while the Gradle devs don't improve the situation.

Add this to your build file:

test {

doFirst {

jvmArgs += [

'--add-exports', "module/package=junit",

]

}

}

Where module/package is the name of the module and package you need to make visible to JUnit.

This is basically equivalent to the exports package to junit clause in module-info.java, but without having the clause make into the compiled jar!

This option is not documented in javac -help, but you can at least find it mentioned in the Oracle JDK Docs and, more thoroughly, in JEP-261... see the Breaking encapsulation section.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值