我正在尝试为类ErParser中的方法setTrailer()
编写测试用例。 setTrailer()
有try-catch子句,并且在其中一个catch子句中,它捕获NullPointerException
。我试图为setTrailer()
引发并捕获NullPointerException
的情况编写Junit测试,但测试用例仍然失败。是否因为我已经在方法本身中发现了异常?我应该在测试用例中捕捉异常吗?Junit已经有try-catch子句的方法的测试用例
测试案例:ERParser类内
public class TestERParser {
@Test(expected=NullPointerException.class)
public void nullSetTrailer() {
ERParser recCurrParse = new ERParser();
recCurrParse.setTrailer(null);
}
}
setTrailer()方法:
public class ERParser {
private static final String TRAILER_E = "GRAND TOTAL";
private static final String TRAILER_R = "TRAILER";
public String trailerRecord;
/**
* Constructs an ERParser object.
*/
public ERParser() {
this.trailerRecord = null;
this.trailerVals = null;
}
/**
* Populates the trailerRecord field with the summary (trailer) record of the input file.
* @param file Input file
* @throws NullPointerException, FileNotFoundException, IOException
*/
public void setTrailer(File file) {
try {
FileReader fReader = new FileReader(file);
BufferedReader bReader = new BufferedReader (fReader);
String currLine = new String();
readLoop:
while (bReader.ready()) {
currLine = bReader.readLine();
if (currLine.contains(TRAILER_E) || currLine.contains(TRAILER_R)) {
break readLoop;
}
}
this.trailerRecord = currLine.trim();
System.out.println("From setTrailer(): " + this.trailerRecord);
fReader.close();
bReader.close();
} catch (NullPointerException exception) {
exception.printStackTrace();
} catch (FileNotFoundException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
}
}
您不应该捕获NPE;你应该完全避免它。检查空值并且没有NPE异常。 –
通常情况下,调用者会抛出并捕获异常,这是执行异常的最佳方式,异常可能是指外部的某种情况;想象除0操作被处理,而不是得到错误,它返回0或1,或任何其他值,但你想期待这种特殊情况。有了Junit,你无法在那里做任何事情,但期待对该方法的调用。如果你抛出任何异常,那么你可以期待异常。 – porfiriopartida
我不认为你完全理解如何从IOException中恢复,只是说。 – Woot4Moo