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

时间:2018-11-17 16:23:09

标签: java junit junit4

我最近开始与Junit合作。

我有一个函数,该函数接收带有从txt文件中获取的值的行,并返回具有该值的实例。

该函数每次接收到错误值时,都会引发异常。

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

@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
}

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

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您已经用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());
}
相关问题