who*_*ami 4 java junit unit-testing mockito
我有一个抽象类BaseTemplate
和多个扩展它的类.在其中一个具体的class(SmsTemplate extends BaseTemplate
)中,我们有一个私有变量Gson
.我们Gson
在抽象类中也有相同的私有变量().
在测试具体类的单元时,抽象类中的方法是从具体类调用的.在我的单元测试中,我Whitebox.setInternalState(smsTemplateObj, gsonObj);
用来将Gson对象注入到私有成员中SmsTemplate
,BaseTemplate
但是Gson只是在子类中注入.在抽象类中,它的NULL
意思是不注入.以下是实施.
请问有人可以告诉如何在抽象类中注入Gson对象吗?
abstract class BaseTemplate{
private Gson gson;//Here its not getting injected
protected String getContent(Content content){
return gson.toJson(content); // ERROR - gson here throws NPE as its not injected
}
}
class SmsTemplate extends BaseTemplate{
private Gson gson;//Here its getting injected
public String processTemplate(Content content){
String strContent = getContent(content);
...
...
gson.fromJson(strContent, Template.class);
}
}
Run Code Online (Sandbox Code Playgroud)
Whitebox.setInternalState()
method只会设置它遇到的第一个字段的值,它通过您传递的对象的层次结构.因此,一旦它gson
在您的子类中找到字段,它将不会进一步查看,也不会更改超类字段.
这种情况有两种解决方案:
Whitebox.setInternalState()
两次,每个变量一次.片段:
Field field = smsTemplateObj.getClass().getSuperclass().getDeclaredField("gson");
field.setAccesible(true);
field.set(smsTemplateObj, gsonObj);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2289 次 |
最近记录: |