为什么可以毫无问题地在 Spock 中测试私有方法/字段?

Xel*_*ian 7 methods unit-testing field private spock

package com.example.dev;
public class AClass {
 private Integer a =10;
...//other code
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的 Spock 方法中访问 a 时:

package com.example.dev;
def 'test a'() {
 AClass aClassVar = new AClass()
 aClassVar.a = new Integer(100);
...//other testing stuff
}
Run Code Online (Sandbox Code Playgroud)

它工作正常。为什么会发生这种情况?Spock 是否使用反射来访问私有字段?还是我的封装没写好?

Opa*_*pal 8

Spock 没有罪,它本身就是 groovy,请参阅:groovy 中的私有方法不是私有的

虽然可以引用类的私有成员,但这绝对不是一个好习惯。

  • @theprogrammer,另请参阅 https://softwareengineering.stackexchange.com/a/100966/177830 和 https://softwareengineering.stackexchange.com/a/375866/177830 及其注释,以了解为什么私有方法不应进行单元测试。 (2认同)