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?
The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.
In short, testing private functions (by using FRIEND_TEST or making them public or using reflection) that could otherwise be tested through a public interface can cause test duplication. You really don't want this, because nothing hurts more than your test suite slowing you down.
So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.
The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true: The private method is dead code. There is a design smell near the class that you are testing.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With