具有特定构造函数的JMockit @Tested字段

时间:2019-03-21 13:58:30

标签: unit-testing jmockit

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

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

代码示例制作课程

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没有注入。

1 个答案:

答案 0 :(得分:0)

我不想更改任何运行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();
    }
}
相关问题