java - How to inject the variable in the abstract class while unit testing the subclass? -


i have abstract class basetemplate , multiple classes extending it. in 1 of concrete class(smstemplate extends basetemplate), have private variable gson. have same private variable(gson) in abstract class well.

while unit tesing concrete class, methods in abstract class getting called concrete class. in unit test, using whitebox.setinternalstate(smstemplateobj, gsonobj); inject gson object private members of smstemplate , basetemplate gson getting injected in subclass. in abstract class, null, meaning not injected. below implementation.

can please tell how inject gson object in abstract class?

abstract class basetemplate{      private gson gson;//here not getting injected      protected string getcontent(content content){         return gson.tojson(content); // error - gson here throws npe not injected     } }  class smstemplate extends basetemplate{      private gson gson;//here getting injected      public string processtemplate(content content){         string strcontent = getcontent(content);         ...         ...         gson.fromjson(strcontent, template.class);     } } 

whitebox.setinternalstate() method set value of first field encounters going through hierarchy of object pass. once finds gson field in subclass, won't further , won't change superclass field.

there 2 solutions case:

  • change variables names. if variables have different names, can invoke whitebox.setinternalstate() twice, 1 each variable.
  • set field manually using reflection. can set field without mockito's using following snippet.

snippet:

field field = smstemplateobj.getclass().getsuperclass().getdeclaredfield("gson"); field.setaccesible(true); field.set(smstemplateobj, gsonobj); 

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 -