代码之家  ›  专栏  ›  技术社区  ›  Lucas Hill

在Gradle中使用JUnit测试抛出的异常

  •  0
  • Lucas Hill  · 技术社区  · 1 年前

    我在Gradle项目中使用JUnit 5。我正试图在P1包中测试此主要功能:

    public static void main(String[] args) {
        // Gets command line arguments
        String fileName = null;
        if (args != null && args.length == 1) {
          fileName = args[0];
        } else {
          throw new IllegalArgumentException("Please specify name of file.");
        }
    
        // Initializes file and scanner from provided path
        File file = new File(fileName);
        Scanner scanner = null;
        try {
          scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
          System.out.println("File not found: " + e.getMessage());
          System.exit(1);
        }
    }
    

    特别是底部的try-catch块。这是我写的测试:

    @Test
    public void testMissingFile() {
        String[] args = { "bad_file" };
        FileNotFoundException thrown = assertThrows(
            FileNotFoundException.class,
            () -> P1.main(args));
    
        assertTrue(thrown.getMessage().contains("File not found:"));
    }
    

    不幸的是,此测试失败,输出来自 gradle test --info :

    TestP1 > testMissingFile() STANDARD_OUT
        File not found: bad_file (No such file or directory)
    

    我试图捕捉这个错误并测试它是否被抛出,但它破坏了测试。我希望测试在检查FileNotFoundException并断言错误消息的内容时通过断言。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Dyjah    1 年前

    您正在捕获代码中的异常并打印错误消息,这正是测试的结果 System.out.println("File not found: + e.getMessage());

    您的代码正在处理异常,因此该异常不会在测试中冒泡。

    如果您想测试它是否抛出异常,您应该删除 try/catch 阻止或在内部引发另一个异常 catch