Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 967
Xelian Avatar asked Oct 20 '14 11:10

Xelian


People also ask

Is it OK to test private methods?

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.

Why don't we test private methods?

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.

Can private methods be tested in JUnit?

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.

Is there any direct way to test private method?

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.


1 Answers

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.

like image 109
Opal Avatar answered Sep 17 '22 14:09

Opal