首页 > 解决方案 > 具有特定构造函数的 JMockit @Tested 字段

问题描述

我正在尝试使用 JMockit 1.45 模拟一个类。由于该Deencapsulation.setField方法已被删除,因此我无法设置私有字段值。因此,我正在寻找一种在启动类时设置私有字段值的方法。我添加了一个额外的构造函数来设置一个私有字段值。但是,我没有找到一种方法来获取@Tested带有特定构造函数注释的属性设置实例。还有其他方法吗?

“long maxSizeByte”应该由配置设置,我需要测试该方法是否在各种值下工作。

代码样例制作类

public class MagazineFetcher {  

    @EJB private StatisticDAO statisticDao;

    // configs
    private long maxSizeByte;

    public MagazineFetcher() {
        this(ProjectConfig.getCdsMaxChannelSizeByte());
    }
    // This constructor is adde for a testcase to set the private value
    public MagazineFetcher(long maxSizeByte) {
        this.maxSizeByte = maxSizeByte;
    }

    // using maxSizeByte field for a calcuation and validation      
    public void doSomething(){
    }
}

测试用例

public class MagazineFetcherTest {
    @Injectable private StatisticDAO statisticDao;

    @Tested private MagazineFetcher magazineFetcher ;

    @Test
    public void testInvalidImportFile() throws Exception {

        magazineFetcher.doSomething();
    }
}

它似乎@Tested private MagazineFetcher magazineFetcher仅由默认构造函数实例化。我正在寻找由另一个构造函数发起的方式。当我简单地MagazineFetcher magazineFetcher = new MagazineFetcher(100 * 1024)然后我得到一个statisticDao没有注入的实例。

标签: unit-testingjmockit

解决方案


我不想更改任何生产代码来运行 JMockit 测试用例。但我必须添加一个方法来模拟它。我很高兴能得到任何更好的主意。

public class MagazineFetcher {  

    @EJB private StatisticDAO statisticDao;

    // configs
    private long maxSizeByte;

    // Method is added only for Testcase
    long getMaxSizeByte() { return maxSizeByte;  }

    public MagazineFetcher() {
        maxSizeByte = ProjectConfig.getCdsMaxChannelSizeByte();
    }
    // No need to add a constructor
    // public MagazineFetcher(long maxSizeByte) {
    //  this.maxSizeByte = maxSizeByte;
    // }

    public void doSomething(){
        // using maxSizeByte field is replaced by getMaxSizeByte() 
        if ( ... < getMaxSizeByte() ) 
            ....
    }
}

测试用例

public class MagazineFetcherTest {
    @Injectable private StatisticDAO statisticDao;

    @Tested private MagazineFetcher magazineFetcher ;

    @Test
    public void testInvalidImportFile() throws Exception {

        new MockUp<MagazineFetcher>(){
            @Mock
            long getMaxSizeByte() {
                return 1024 * 1024 * 250;
            }
        };

        magazineFetcher.doSomething();
    }
}

推荐阅读