java - Accessing private members for unit testing -


usually when i'm writing unit test in c++, declare test class friend tesee. way can inspect results of operation directly inspecting member variables. java not have friends, how achieve same behavior? i'm not talking simple getters , setters here testing trivial, situations results of operation stored internally in class , it's not exposed outside world.

if don't want use frameworks can 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 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 can move test classes same package tested class , use package-private (no explicit modifier) field or method. more details read controlling access members of class


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -