【发布时间】:2015-08-05 11:27:16
【问题描述】:
我有一个抽象类BaseTemplate 和多个扩展它的类。在其中一个具体类(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);
}
}
【问题讨论】:
-
使抽象类的字段受保护,并从子类中删除删除字段。
-
@Stefan - 啊……问题是,Gson 对象并未在所有具体类中使用。
-
为什么在抽象类和子类中需要一个gson变量?
-
@bryce - 在抽象类和子类中(不是在所有子类中),显然都需要 gson 对象。
-
如果不是所有具体类都需要 Gson 对象,则需要第二层抽象。没有 Gson 的 BaseTemplate 是一个扩展 BaseTemplate 的抽象类,在这个类中是 Gson 对象。不需要 Gson 对象的具体类扩展 BaseTemplate 和其他扩展你的第二个抽象类
标签: java unit-testing junit mockito