我正在尝试为我的suchAutor()
方法编写一个JUnit。
问题是我抛出了两个不同的异常,我只知道如何处理抛出一个异常的测试。
public Buch[] suchAutor(String gesuchterName) throws IllegalArgumentException, FileNotFoundException {
if (gesuchterName == "") {
throw new IllegalArgumentException("Bitte geben sie einen Nachnamen ein.");
}
Buch[] erg = new Buch[0];
int arraylength = 0;
Boolean found = false;
for (int i = 0; i < buecher.length; i++) {
for (int u = 0; u < buecher[i].getAutoren().length; u++) {
if (buecher[i].getAutoren()[u].getNachname() == gesuchterName) {
found = true;
arraylength++;
erg = Arrays.copyOf(erg, arraylength);
erg[arraylength - 1] = buecher[i];
}
}
}
if (found) {
System.out.println(Arrays.toString(erg));
return erg;
} else {
throw new FileNotFoundException("Zu dem gesuchten Autor wurden keine Bücher gefunden.");
}
}
@Test(expected = Exception.class)
public void testSuchAutorGrenzwert() {
try {
bibliothek.suchAutor("");
} catch (IllegalArgumentException e) {
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
答案 0 :(得分:3)
该问题被标记为junit5,并且木星具有专门专用的assertThrows工具:
@Test
void failsOnEmptyName(){
assertThrows(IllegalArgumentException.class, ()-> bibliothek.suchAutor(""));
}
答案 1 :(得分:2)
假设Junit4:
public class MyTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void myTest() throws IllegalArgumentException, FileNotFoundException {
thrown.expect(IllegalArgumentException.class);
myObject.suchAutor("");
}
@Test
public void myOtherTest() throws IllegalArgumentException, FileNotFoundException {
thrown.expect(FileNotFoundException.class);
myObject.suchAutor("An Unknown Autor");
}
}
在上文中,我们使用相同的规则,即以下代码应引发并抛出异常,如果测试未引发并抛出异常或抛出IllegalArgumentException
以外的异常,则测试将失败。
我们将规则设置为默认情况下不会出现异常,任何未测试异常的测试均应正常工作。
请参阅JUnit Docs
答案 2 :(得分:-1)
我只是按下快速修复,现在可以使用:D
@Test
public void testSuchAutorGrenzwert() {
try {
bibliothek.suchAutor("");
} catch (IllegalArgumentException | FileNotFoundException e) {
// TODO Auto-generated catch block
e.getMessage();
}
}