当测试预期异常时,assertEquals 不显示错误

assertEquals doesn't show errors when the test is expecting exceptions

我最近开始使用 Junit。

我有一个函数可以接收包含从 txt 文件中获取的值的行,以及包含该值的 returns 个实例。

每当该函数接收到错误值时,我都会抛出异常。

我的测试方法是验证异常是否工作正常,以及实例返回的值是否正确。

@Test(expected = StudentException.class)
public void testImportStudent() {
    String txtline = "1, Name, Name"; //Wrong, It should be 1, Name
    Source test = studentMain.importStudent(txtline); //Throw error
    txtline = "1, Name"; //Right
    test = percursoGestor.importSource(line); //Test passed
    assertEquals("Error inserting ID", 3, test.getStudentID()); //Test ignores this line
    assertEquals("Error inserting Name", "Nothing", test.getStudentName()); //Test ignores this line
}

因此,我的测试检查是否引发了错误,但忽略了 assertequals,即使我输入的值与预期的不同,测试也通过了。因为我期待抛出异常。

我做错了什么?

您已经用 expected = StudentException.class 注释了您的测试方法。

这基本上是在整个方法周围放置一个 try-catch 块:

@Test(expected = StudentException.class)
public void testImportStudent() {
    try {
        String txtline = "1, Name, Name";
        Source test = studentMain.importStudent(txtline); //Throw error
        txtline = "1, Name";
        test = percursoGestor.importSource(line);
        assertEquals("Error inserting ID", 3, test.getStudentID());
        assertEquals("Error inserting Name", "Nothing", test.getStudentName());
    } catch (Exception e) {
        // verify exception
    }
}

和往常一样:抛出异常后不执行任何操作。

干净的方法是使用两个单独的方法:

@Test(expected = StudentException.class)
public void testImportStudent_incorrectInput() {
    String txtline = "1, Name, Name";
    Source test = studentMain.importStudent(txtline);
}

@Test
public void testImportStudent_correctInput() {
    String txtline = "1, Name";
    Source test = percursoGestor.importSource(line);
    assertEquals("Error inserting ID", 3, test.getStudentID());
    assertEquals("Error inserting Name", "Nothing", test.getStudentName());    
}

如果您真的想用一种方法测试多个案例(您可能不想),那么您可以自己使用try-catch

@Test
public void testImportStudent() {
    String txtline = "1, Name, Name";
    Source test;
    try {
        test = studentMain.importStudent(txtline);
        // Make sure that the test fails when no exception is thrown
        fail();
    } catch (Exception e) {
        // Check for the correct exception type
        assertTrue(e instanceof StudentException);
    }
    // Other checks
    txtline = "1, Name";
    test = percursoGestor.importSource(line);
    assertEquals("Error inserting ID", 3, test.getStudentID());
    assertEquals("Error inserting Name", "Nothing", test.getStudentName());
}