您已使用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());
}