如何用JUnit或Mockito测试模拟配置文件不存在场景?
测试Properties文件不存在场景时无法触发Catch块的解决思路
我尝试测试模拟Properties文件不存在的场景,但无法触发catch代码块,请问有什么解决思路?
CRentaProperties类构造方法代码
public CRentaProperties() throws IOException { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream("/home/m1/conf/config.properties"); } catch (FileNotFoundException e) { log.error("ARCHIVO DE PROPIEDADES NO ENCONTRADO EN SERVIDOR", e); try { input = new FileInputStream("config.properties"); } catch (FileNotFoundException e1) { log.error("ARCHIVO DE PROPIEDADES NO ENCONTRADO EN PROYECTO", e1); } } try { prop.load(input); } catch (IOException e) { log.error("[ERROR DE PROPERTIES]", e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { log.error("Error al cerrar el archivo", e); } } } }
当前正常读取的测试代码
class CRentaPropertiesTest { @Test void testUtilPropertiesTest() { CRentaProperties properties = null; try { properties = new CRentaProperties(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { CRentaProperties.getCRentaUtilsProperties(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertEquals("Queue" , properties.getqQueue()); assertEquals("MANAGER" , properties.getqManager()); assertEquals("14" , properties.getqPort()); assertEquals("CHANNEL" , properties.getqChannel()); assertNotNull( properties.getqManager()); } }
解决思路
- 抽取文件路径为可配置参数:把硬编码的文件路径从构造方法中抽离,改为通过构造方法参数传入或静态配置项设置。测试时直接传入不存在的路径,即可触发
FileNotFoundException。 - 修改异常逻辑主动抛出异常:当前代码中,两个文件都找不到时仅打印日志,不会抛出异常导致测试无法捕获。需在第二个
FileNotFoundException的catch块中主动抛出异常,确保构造方法的throws声明包含该异常类型:catch (FileNotFoundException e1) { log.error("ARCHIVO DE PROPIEDADES NO ENCONTRADO EN PROYECTO", e1); throw e1; // 主动抛出异常供上层捕获 } - 用PowerMock拦截构造调用:若无法修改原代码的路径硬编码,可使用PowerMock框架拦截
new FileInputStream()的调用,强制抛出异常。示例代码(需引入PowerMock依赖):@RunWith(PowerMockRunner.class) @PrepareForTest(CRentaProperties.class) class CRentaPropertiesTest { @Test void testPropertiesFileNotFound() throws Exception { // 拦截两个路径的FileInputStream构造,均抛出异常 PowerMock.expectNew(FileInputStream.class, "/home/m1/conf/config.properties") .andThrow(new FileNotFoundException()); PowerMock.expectNew(FileInputStream.class, "config.properties") .andThrow(new FileNotFoundException()); PowerMock.replayAll(); // 断言创建实例时会抛出异常 assertThrows(FileNotFoundException.class, CRentaProperties::new); PowerMock.verifyAll(); } } - 新增异常场景测试用例:当前测试仅覆盖正常读取场景,需新增专门测试方法,用
assertThrows断言文件不存在时的异常是否被正确抛出。
内容的提问来源于stack exchange,提问作者Adiel Trigueros
相关产品推荐
相关产品推荐

