Why can test private methods/fields in Spock without problems?

折月煮酒 提交于 2019-12-04 15:18:45

问题


package com.example.dev;
public class AClass {
 private Integer a =10;
...//other code
}

and when I try to access a in my Spock method:

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

It works fine. Why this happens? Is Spock use reflection for accessing the private fields? Or my encapsulation in not written well?


回答1:


Spock isn't guilty, it's groovy itself, see: Private method in groovy is not private.

While it's possible to refer to private members of class, it's definitely not a good practice.




回答2:


It's my understanding that

aClassVar.a = new Integer(100)

in Groovy / Spock is just syntactic sugar for

aClassVar.setA(new Integer(100));

in Java. There have been occasions where I tried to do that and there WASN'T a setter and Spock griped.

As for why we create private attributes and then give them setters, THAT is another discussion.



来源:https://stackoverflow.com/questions/26464980/why-can-test-private-methods-fields-in-spock-without-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!