我一直在尝试为JUnit 5测试创建一个测试用例,但似乎总是遇到心理障碍。基本上,我有一个程序,从fileInputStream计数单词,然后排序它们。我已经提出的测试用例将验证几个不同单词的计数,但不确定如何使用JUnit 5实现它。我正在尝试测试的代码片段如下所示:
public class wordPopulation {
public static void main(String[] args) throws IOException {
FileInputStream findIt = new FileInputStream("theraven.txt");
Scanner fileInput = new Scanner(findIt);
ArrayList<String> words = new ArrayList<String>();
ArrayList<Integer> count = new ArrayList<Integer>();
while (fileInput.hasNext()) {
String nextWord = fileInput.next();
if (words.contains(nextWord)) {
int index = words.indexOf(nextWord);
count.set(index, count.get(index)+ 1);
}
else {
words.add(nextWord);
count.add(1);
}
}
fileInput.close();
findIt.close();
for (int i = 0; i < words.size(); ++i) {
Collections.sort(count, Collections.reverseOrder());
try(FileWriter fw = new FileWriter("theraven.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw)) {
out.println();
out.println(words.get(i) + " occurred " + count.get(i) + " times ");
} catch (IOException e) {
}
}
}
}
1条答案
按热度按时间l0oc07j21#
From what I understand you want to:
To test your code you basically need to put everything in a function that will take a file path as input, and will return the sorted list as output.
In your test scenarios you will then be able to reuse your function with multiple text files from which you exactly know the result (very simple text files with very previsible array outcomes) You then manually build the array objects that match every file you want to test and call an assert equal function between your function output and the result you manually built.
Your tests could have an init phase where is will create the text files and a post test phase where it will delete them.
ex: for sum(int a, int b){ return a + b;} we do:
You don't want to recode your functions into your test scenarios, you want to compare your function results with previsible outcomes.