java 如何测试从文件和路径读取(使用junit)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14527074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:33:08  来源:igfitidea点击:

How to test read from file and path (using junit)?

javatestingfile-iojunitpath

提问by Upgradingdave

I need to execute test coverage with the JUnit framework.

我需要使用 JUnit 框架执行测试覆盖率。

I read JUnit - Tutorialbut I can't bind this knowledge with my example.

我阅读了JUnit - 教程,但我无法将这些知识与我的示例结合起来。

I understand how I can test method read from file alone but don't know how do this completely with test some path and askUserPathAndWord. How can I make good tests for this?

我了解如何测试单独从文件中读取的方法,但不知道如何通过测试某些路径和 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();
    }
}

Next questions:

接下来的问题:

  • How we can completely test integration dependencies and check path?
  • Which point should have good, understandably junit test?
  • Do we need use fail test in this situations?
  • Which max percent program we can cover?
  • Should we test private and protected methods (generally)?
  • 我们如何完全测试集成依赖项并检查路径?
  • 哪一点应该有好的,可以理解的junit测试?
  • 在这种情况下我们是否需要使用失败测试?
  • 我们可以涵盖哪个最大百分比计划?
  • 我们应该测试私有和受保护的方法(通常)吗?

回答by Upgradingdave

I suggest keeping it simple to start with. In my mind, at a fundamental level, the goal of writing unit tests is to really just to ensure that your code does what intended it to do.

我建议一开始就保持简单。在我看来,从根本上讲,编写单元测试的目标实际上只是为了确保您的代码按预期执行。

I think your readmethod is a good place to start. It looks like the purpose of your readmethod is to take a file name as input and return a string containing the files contents.

我认为你的read方法是一个很好的起点。看起来您的read方法的目的是将文件名作为输入并返回包含文件内容的字符串。

So, to write a test that proves that it works, first create a file named "testFile" somewhere with some dummy text inside the file such as "my test".

因此,要编写一个证明它有效的测试,首先在文件中的某处创建一个名为“testFile”的文件,其中包含一些虚拟文本,例如“我的测试”。

Then, write a unit test like:

然后,编写一个单元测试,如:

@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);

}

That's just to get you started. Once you get the hang of it, you can make improvements such as updating the path to the test file so that it isn't hardcoded. Ideally, the test should be able to run from anywhere.

这只是让你开始。一旦掌握了窍门,就可以进行改进,例如更新测试文件的路径,使其不会被硬编码。理想情况下,测试应该能够从任何地方运行。

As a nice extra bonus, writing unit tests makes you think about organizing your packages, classes and methods in such a way that they are more reusable and easier to understand (in addition to other benefits as well).

作为一个额外的好处,编写单元测试让您考虑以更可重用和更易于理解的方式组织包、类和方法(除了其他好处之外)。

For example, your walkmethod is difficult to test as it's currently written. So try and think about how to make it easier to test. Maybe it can return a List of Strings representing the search results? If you make that change and search the directory containing testFile for the string "test", you know you should get one result in the list, so test for that using something like:

例如,您的walk方法很难测试,因为它目前是编写的。因此,请尝试考虑如何使其更易于测试。也许它可以返回一个代表搜索结果的字符串列表?如果您进行更改并在包含 testFile 的目录中搜索字符串“test”,您知道应该在列表中得到一个结果,因此请使用以下内容进行测试:

assertNotNull(searchPhrase.walk());
assertEquals(1, searchPhrase.walk().size());

Since you're just starting out, I suggest not to worry about percent of program your tests cover.

由于您刚刚开始,我建议不要担心您的测试涵盖的程序百分比。

When writing tests, it helps me to think about if someone else were to use my code, how would they expect it to behave? Then I try and write tests that demonstrate the intended behavior.

在编写测试时,它帮助我思考如果其他人要使用我的代码,他们会期望它的行为如何?然后我尝试编写测试来演示预期的行为。

Hope that helps!

希望有帮助!