java - 对构造函数方法进行单元测试
问题描述
我很难理解如何对构造函数方法进行单元测试。
我需要检查是否引发了错误。构造函数是:
@Autowired
public BankDetailsValidator() {
try {
logDebugMessage("BankDetailsValidator() constructor");
loadModulusWeightTable();
loadSortCodeSubstitutionTable();
} catch (final IOException e) {
throw new BankDetailsValidationRuntimeException("An error occured loading the modulus weight table or sort code substitution table", e);
}
}
要对此进行测试,我需要使用loadModulusWeightTable
or loadSortCodeSubstitutionTable
throw and IOException
。
private void loadModulusWeightTable() throws IOException {
modulusWeightTable.clear();
logDebugMessage("Attempting to load modulus weight table " + MODULUS_WEIGHT_TABLE);
final InputStream in = new FileInputStream(MODULUS_WEIGHT_TABLE);
br = new BufferedReader(new InputStreamReader(in));
try {
String line;
while ((line = br.readLine()) != null) {
final String[] fields = line.split("\\s+");
modulusWeightTable.add(new ModulusWeightTableEntry(fields));
}
logDebugMessage("Modulus weight table loaded");
}
finally {
br.close();
}
}
我试图让Spy
缓冲文件阅读器返回 aIOException
但由于它位于构造函数中而无法使其工作。
public class BankDetailsValidatorTest {
@Spy
private BufferedReader mockBufferReader;
@InjectMocks
private CDLBankDetailsValidator testSubject;
@Test(expected = IOException.class)
public void testIOErrorLogging() throws Exception{
when(mockBufferReader.readLine()).thenThrow(new IOException());
testSubject = new CDLBankDetailsValidator();
}
}
解决方案
我认为应该重构 BankDetailsValidator 类。在这种情况下,您应该将负责读取数据的代码提取到单独的类中,并将其作为构造函数参数注入 BankDetailsValidator。之后,您可以单独测试该阅读器,当然还可以使用模拟阅读器测试 BankDetailsValidator。
推荐阅读
- angular - 将元素添加到模型
- python - 如何修复 Flask-uwsgi-Nginx 设置中的 Post 请求延迟的 websocket 消息?
- java - 如何向有效负载表达式添加两个路径变量?
- python - Quart Bad Request 语法或不支持的方法
- python-3.x - 将 .py 文件导入另一个脚本以使用其中的变量,其中导入文件由 "if __name__ == '__main__' 运行
- jquery - 获取特定 ID 的值并显示在该行的特定字段上
- javascript - 单击表格行时如何从单元格中获取值
- php - Wordpress 侧边栏子列表中的缩略图
- css - 我想在显示警报时移动 div
- python - 硬编码密码/凭据