我需要使用 JUnit 框架执行测试覆盖。
我阅读了JUnit - 教程,但我无法将这些知识与我的示例绑定。
我了解如何单独测试从文件中读取的方法,但不知道如何通过测试某些路径和 askUserPathAndWord 来完全做到这一点。我怎样才能对此进行良好的测试?
package task;
import java.io.*;
class SearchPhrase {
public void walk(String path, String whatFind) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
for (File titleName : list) {
if (titleName.isDirectory()) {
walk(titleName.getAbsolutePath(), whatFind);
} else {
if (read(titleName.getAbsolutePath()).contains(whatFind)) {
System.out.println("File:" + titleName.getAbsolutePath());
}
}
}
}
// Read file as one line
public static String read(String fileName) {
StringBuilder strBuider = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader(new File(
fileName)));
String strInput;
while ((strInput = in.readLine()) != null) {
strBuider.append(strInput);
strBuider.append("\n");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return strBuider.toString();
}
public void askUserPathAndWord() {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in));
String path, whatFind;
try {
System.out.println("Please, enter a Path and Word"
+ "(which you want to find):");
System.out.println("Please enter a Path:");
path = bufferedReader.readLine();
System.out.println("Please enter a Word:");
whatFind = bufferedReader.readLine();
if (path != null && whatFind != null) {
walk(path, whatFind);
System.out.println("Thank you!");
} else {
System.out.println("You did not enter anything");
}
} catch (IOException | RuntimeException e) {
System.out.println("Wrong input!");
e.printStackTrace();
}
}
public static void main(String[] args) {
SearchPhrase example = new SearchPhrase();
example.askUserPathAndWord();
}
}
接下来的问题:
- 我们如何才能完全测试集成依赖并检查路径?
- 哪一点应该有好的,可以理解的junit测试?
- 在这种情况下我们需要使用失败测试吗?
- 我们可以覆盖哪个最大百分比计划?
- 我们应该(通常)测试私有方法和受保护方法吗?