在对子类进行单元测试时,如何在抽象类中注入变量? [英] How to inject the variable in the abstract class while unit testing the subclass?

查看:231
本文介绍了在对子类进行单元测试时,如何在抽象类中注入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类BaseTemplate和多个扩展它的类.在一个具体的类(SmsTemplate extends BaseTemplate)中,我们有一个私有变量Gson.我们在抽象类中也有相同的私有变量(Gson).

I have an abstract class BaseTemplate and multiple classes extending it. In one of the concrete class(SmsTemplate extends BaseTemplate), we have a private variable Gson. We have the same private variable(Gson) in the abstract class as well.

在设置具体类的单元时,抽象类中的方法从具体类中被调用.在单元测试中,我正在使用Whitebox.setInternalState(smsTemplateObj, gsonObj);将Gson对象注入到SmsTemplateBaseTemplate的私有成员中,但是Gson仅在子类中被注入.在抽象类中,其NULL表示未注入.下面是实现.

While unit tesing the concrete class, methods in the abstract class is getting called from the concrete class. In my Unit test, I am using Whitebox.setInternalState(smsTemplateObj, gsonObj); to inject the Gson object into the private members of SmsTemplate and BaseTemplate but the Gson is getting injected only in the subclass. In abstract class, its NULL, meaning not injected. Below is the implementation.

有人可以告诉我如何在抽象类中注入Gson对象吗?

Can someone please tell how to inject the Gson object in the abstract class?

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);
    }
}

推荐答案

Whitebox.setInternalState()方法将仅设置在您传递的对象的层次结构中遇到的第一个字段的值.因此,一旦在子类中找到gson字段,它就不会看起来更远,也不会更改超类字段.

Whitebox.setInternalState() method will only set the value of the first field it encounters going up through the hierarchy of the object you pass. So once it finds gson field in your subclass, it won't look further and won't change the superclass field.

有两种解决方案:

  • 更改变量名称.如果变量具有不同的名称,则可以简单地调用Whitebox.setInternalState()两次,每个变量一次.
  • 使用反射手动设置字段.您也可以在没有Mockito帮助的情况下使用以下代码段设置字段.
  • Change the variables names. If the variables have different names, you can simply invoke Whitebox.setInternalState() twice, one for each variable.
  • Set the field manually using reflection. You can also just set the field without Mockito's help using something like the following snippet.

摘要:

Field field = smsTemplateObj.getClass().getSuperclass().getDeclaredField("gson");
field.setAccesible(true);
field.set(smsTemplateObj, gsonObj);

这篇关于在对子类进行单元测试时,如何在抽象类中注入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆