i read question: how test class has private methods, fields or inner classes? , seems might have code smell, code simple refactor. wrong in design have created. have created delegate class processing actions has 3 methods execute(action);
populateactionhandlers()
, executeactionhandlers();
class below:
public class delegatehandler{ map<integer,actionhandlers> handlermaps; public execute(action action){ populateactionhandlers(action); executeactionhandlers(); }//end of execute //this method can create , populate more 1 handlers in handlermap private populateactionhandlers(action){ handlermap = new linkedhashmap<actionhandlers>(); if (action.ismultimode()){ handlermap.add(1,new handler(action.getabc())); handlermap.add(2,new handler(action.getabc()-1)); }else{ handlermap.add(1,new handler(action)); } }//end of populateactionhandlers //this method can execute more 1 handlers in handlermap private executeactionhandlers(){ for(actionhandler actionhandler : handlermap.values){ actionhandler.executeaction(); } }//end of executeactionhandlers }
now want test populateactionhandlers()
method junit, made private there no need expose outside class. if test execute()
method test both populateactionhandlers()
, executeactionhandlers()
methods testing 2 units @ same time, want test them separately. design (i think) seems alright me , doesnt allow issues either change access method (and sake of testing doesn't justify in opinion, right?) or use reflection (is idea, not feel right somehow, people use reflection junit testing?). thing cant ruled out code smell. may code sinus not helping me understand if can improve code.
the recommendation not test private methods should not prevent 1 weird design leaving out private method, should enforce test methods have clear semantics.
private methods technical helpers. semantics can change if underlying data structures change, can optimized away if calling public methods use algorithm achieve same goals.
i rewrite programm in following way:
... public execute(action action){ map<integer,actionhandlers> handlermap = populateactionhandlers(action); executeactionhandlers(handlermap); } ...
storing results of 1 function private field retrieve field in function not threadsafe , harder maintain.
yet refactoring break (yet not writte) tests did test private method of example, because interface changed. if had tested public method, tests valid after refactoring.
i know few cases testing private methods ok. while testing private methods avoidable, think checking of private state better alternative checking public state of objects. such checks may not robust (reasons above) public state incomplete , hard assert. in both cases use framework picklock enables 1 access private methods , fields in convenient way.