为什么JUnit 5默认访问修饰符更改为package-private

woj*_*902 11 java encapsulation package-private junit5

为什么JUnit 5 package-private中的默认访问修饰符是?

JUnit 4中的测试必须是公开的。

将其更改为程序包专用有什么好处?

Sam*_*nen 12

为什么JUnit 5 package-private中的默认访问修饰符是?

It's not the "default". There technically is no default. Rather, in JUnit Jupiter you have a choice: public, protected or package-private.

What is the benefit of changing it to package-private?

The benefit is that you don't have type public anymore. If your IDE automatically generates test methods and test classes for you that are public, feel free to leave them public.

But... if you are typing in the methods on your own, then just leave off public unless you are designing your test classes for subclassing from other packages, in which case you'd want to make your overrideable test methods either public or protected. And of course, interface default methods must be public.

Long story, short: we (the JUnit 5 team) believe in the principle "Less is more", meaning the less you have to type to achieve your goal, the better!

  • 我想提供另一种观点:在这种情况下,更少的打字也意味着更少的表达能力。当我公开测试时,我表达了这样一个事实:测试暴露给外部调用者(测试框架),就像我编写一个供另一个应用程序使用的库一样。当使用其他访问修饰符时,JUnit 必须使用反射在运行时更改它们。虽然从技术上讲可以省略访问修饰符,但我选择显式添加它。对我来说添加 public 是向 JUnit 和其他开发人员表达我的意图的最佳方式。 (4认同)

use*_*900 5

这是 JUnit 5特性,它为测试类和方法产生更好的封装

将 Jupiter 测试包设为私有 #679

测试类主要位于测试类的同一个包中:

更好的方法是将测试放置在具有包对齐的单独并行目录结构中。

main/                          test/
   com/                           com/
      xyz/                           xyz/
          SomeClass.java               SomeClassTests.java
Run Code Online (Sandbox Code Playgroud)

这种方法允许测试代码访问被测类的所有公共和包可见成员。

  • 我需要在测试中封装什么? (3认同)
  • 老实说,这并不能说服我......我看不到测试封装有任何好处...... (2认同)