我试图用JMockit 1.45模拟一个类。由于删除了Deencapsulation.setField
方法,我无法设置私有字段值。所以我正在寻找一种方法来在启动类时设置私有字段值。我添加了一个额外的构造函数来设置私有字段值。但是,我找不到一种方法来获得一个带有特殊构造函数的@Tested
注释的自制实例。还有其他办法吗?
应该通过Configuration设置“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
仅由Default Constructor实例化。我正在寻找由另一个构造函数启动的方法。当我只是MagazineFetcher magazineFetcher = new MagazineFetcher(100 * 1024)
然后我得到一个不注入statisticDao
的实例。
我不想更改运行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();
}
}