0

Usually when I'm writing an unit test in C++, I declare the test class friend to the tesee. That way I can inspect the results of the operation directly by inspecting the member variables. Java does not have friends, so how do you achieve the same behavior? I'm not talking about simple getters and setters here where testing is trivial, but situations where the results of the operation are stored internally in the class and it's not exposed to the outside world.

ventsyv
  • 3,316
  • 3
  • 27
  • 49
  • 1
    possible duplicate of [How to test a class that has private methods, fields or inner classes](http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes) – user1438038 Jul 23 '15 at 19:36

2 Answers2

0

You could use PowerMock framework to mock a private member in a given class. You can refer to the link for examples on how to do that.

Some guy
  • 1,210
  • 1
  • 17
  • 39
0

If you don't want to use frameworks you can do it with Java reflections

Accessing value of private field using reflection in Java

Person privateRyan = new Person("John" , "8989736353");
Field privateField = person.getDeclaredField("phone");

//this call allows private fields to be accessed via reflection
privateField.setAccessible(true);

//getting value of private field using reflection
String value = (String) privateField.get(privateRyan);

Accessing private method using reflection

Method privateMethod = person.getDeclaredMethod("call");

//making private method accessible using reflection
privateMethod.setAccessible(true);

//calling private method using reflection in java
privateMethod.invoke(privateRyan);

(from: http://javarevisited.blogspot.com/2012/05/how-to-access-private-field-and-method.html)

Also you can move test classes into the same package that tested class is and use package-private (no explicit modifier) for field or method. For more details read Controlling Access to Members of a Class

Ivan Makhnyk
  • 106
  • 6