简体   繁体   English

如何对读取给定文件的方法进行单元测试

[英]How to unit test a method that reads a given file

I know this is a bit naive. 我知道这有点天真。 How to unit test this piece of code without giving physical file as input. 如何在不提供物理文件作为输入的情况下对这段代码进行单元测试。 I am new to mockito and unit testing. 我是模拟和单元测试的新手。 So I am not sure. 所以我不确定。 Please help. 请帮忙。

public static String fileToString(File file) throws IOException
{
    BufferedReader br = new BufferedReader(new FileReader(file));
    try {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append("\n");
            line = br.readLine();
        }
        return sb.toString();
    } finally {
        br.close();
    }
}

You can create a file as part of the test, no need to mock it out. 您可以创建一个文件作为测试的一部分,无需模拟它。

JUnit does have a nice functionality for creating files used for testing and automatically cleaning them up using the TemporaryFolder rule. JUnit确实有一个很好的功能,可以创建用于测试的文件,并使用TemporaryFolder规则自动清理它们。

public class MyTestClass {

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();

    @Test
    public void myTest() {
        // this folder gets cleaned up automatically by JUnit
        File file = folder.newFile("someTestFile.txt");

        // populate the file
        // run your test
    }
}

You should probably refactor your method. 你应该重构你的方法。 As you realized, a method taking a file as input isn't easily testable. 如您所知,将文件作为输入的方法不容易测试。 Also, it seems to be static, which doesn't help testability. 此外,它似乎是静态的,这无助于可测试性。 If you rewrite your method as : 如果您将方法重写为:

public String fileToString(BufferedReader input) throws IOException

it will be much easier to test. 它会更容易测试。 You separate your business logic form the technicalities of reading a file. 您将业务逻辑与读取文件的技术分开。 As I understand it, your business logic is reading a stream and ensuring the line endings are unix style. 据我所知,您的业务逻辑是读取流并确保行结尾是unix样式。

If you do that, your method will be testable. 如果你这样做,你的方法将是可测试的。 You also make it more generic : it can now read from a file, from a URL, or from any kind of stream. 您还可以使它更通用:它现在可以从文件,URL或任何类型的流中读取。 Better code, easier to test ... 更好的代码,更容易测试......

Why do you wanna mock a file? 你为什么要模拟文件? Mocking java.io.File is a bad idea as it has loads of native stuff. 模拟java.io.File是一个坏主意,因为它有大量本机的东西。 I would advice you to ensure that a minimalist text file is available in classpath when the unit tests are run. 我建议你在运行单元测试时确保在类路径中有一个极简主义的文本文件。 You can convert this file to text and confirm the output. 您可以将此文件转换为文本并确认输出。

you could use combination of ByteArrayInputStream and BufferedReader class, to make your required file within your code. 您可以使用ByteArrayInputStream和BufferedReader类的组合,在您的代码中创建所需的文件。 So there wouldn't be any need to create a real File on your system. 因此,不需要在您的系统上创建真正的文件。 What would happen if you don't have enough permission --based of some specific circumstances -- to create a file. 如果您没有足够的权限(基于某些特定情况)来创建文件,会发生什么。 On the code below, you create your own desirable content of your file: 在下面的代码中,您可以创建自己想要的文件内容:

public static void main(String a[]){

    String str = "converting to input stream"+
                    "\n and this is second line";
    byte[] content = str.getBytes();
    InputStream is = null;
    BufferedReader bfReader = null;
    try {
        is = new ByteArrayInputStream(content);
        bfReader = new BufferedReader(new InputStreamReader(is));
        String temp = null;
        while((temp = bfReader.readLine()) != null){
            System.out.println(temp);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try{
            if(is != null) is.close();
        } catch (Exception ex){

        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM