2 java testing file-io junit path
我需要使用JUnit框架执行测试覆盖.
我读了JUnit - Tutorial但是我无法将这些知识与我的例子绑定.
我理解如何单独测试文件中的方法读取,但不知道如何完全测试一些路径和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();
}
}
Run Code Online (Sandbox Code Playgroud)
下一个问题:
我建议保持简单开头.在我看来,从根本上讲,编写单元测试的目的只是为了确保您的代码能够完成预期的操作.
我认为你的read方法是一个很好的起点.看起来你的read方法的目的是将文件名作为输入并返回包含文件内容的字符串.
因此,要编写一个证明它有效的测试,首先在文件中创建一个名为"testFile"的文件,其中包含一些虚拟文本,例如"my test".
然后,写一个单元测试,如:
@Test
public void read() {
String testFileName = "/path/to/test/file/testFile";
String expected = "my test";
SearchPhrase searchPhrase = new SearchPhrase();
String result = searchPhrase.read(testFileName);
assertEquals(expected, result);
}
Run Code Online (Sandbox Code Playgroud)
那只是为了让你开始.一旦掌握了它,就可以进行改进,例如更新测试文件的路径,使其不是硬编码的.理想情况下,测试应该能够从任何地方运行.
作为一个很好的额外奖励,编写单元测试可以让您考虑以更加可重用和易于理解的方式组织您的包,类和方法(除了其他好处之外).
例如,您的walk方法很难测试,因为它是当前编写的.因此,请尝试考虑如何使其更容易测试.也许它可以返回代表搜索结果的字符串列表?如果您进行了更改并在包含testFile的目录中搜索字符串"test",那么您知道应该在列表中获得一个结果,因此请使用以下内容对其进行测试:
assertNotNull(searchPhrase.walk());
assertEquals(1, searchPhrase.walk().size());
Run Code Online (Sandbox Code Playgroud)
由于您刚刚开始,我建议不要担心您的测试涵盖的程序百分比.
在编写测试时,它可以帮助我思考是否有其他人使用我的代码,他们会如何表现?然后我尝试编写演示预期行为的测试.
希望有所帮助!
| 归档时间: |
|
| 查看次数: |
14697 次 |
| 最近记录: |