unit-testing - 具有特定构造函数的 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
没有注入的实例。
解决方案
我不想更改任何生产代码来运行 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();
}
}
推荐阅读
- ssl - 在 Maximo/Jython 中下载 SetupTools 失败并出现 HTTP 错误 403 SSL is required
- python-3.x - 在熊猫数据框中创建一列
- node.js - 数据库猫鼬中的文本搜索
- bash - 根据序列号从文件中删除一行?
- java - 如何在 Android Studio 上使用 html 打开新活动
- python - bash vs python中的gzip
- c# - ArgumentException:值不在预期范围内。System.Net.Sockets.Socket.SetSocketOption
- visual-studio - DeploymentEnabled false 在我的运行设置文件中不起作用
- python - Python3 / Tkinter for循环显示带有图像的按钮
- robotframework - 无法使用 Robotframework-databaselibrary 连接到 Excel 作为数据库