gpt4 book ai didi

java - 已具有 try-catch 子句的方法的 Junit 测试用例

转载 作者:行者123 更新时间:2023-12-02 06:42:35 24 4
gpt4 key购买 nike

我正在尝试为 ErParser 类中的 setTrailer() 方法编写一个测试用例。 setTrailer() 具有 try-catch 子句,并且在其中一个 catch 子句中,它捕获 NullPointerException。我正在尝试为 setTrailer() 抛出并捕获 NullPointerException 的情况编写 Junit 测试,但测试用例始终失败。是因为我已经在方法本身中捕获了异常吗?我应该在测试用例中捕获异常吗?

测试用例:

public class TestERParser { 
@Test(expected=NullPointerException.class)
public void nullSetTrailer() {
ERParser recCurrParse = new ERParser();
recCurrParse.setTrailer(null);
}
}

ERParser 类中的 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,并且它没有被传播。如果您希望用户捕获此异常,您应该删除此代码并用 throws 装饰您的方法到适当的类。

public void setTrailer(File file) throws Exception {
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();
}

由于您的代码现在抛出已检查的异常,因此您需要稍微更新您的 Junit 方法,以捕获已检查的异常

   @Test(expected=NullPointerException.class)
public void nullSetTrailer() throws Exception {
ERParser recCurrParse = new ERParser();
recCurrParse.setTrailer(null);
}

关于java - 已具有 try-catch 子句的方法的 Junit 测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18993638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com