Junit测试通过在私有方法内部传递文件路径字符串和IOException处理

问题描述 投票:1回答:2

我有一个从main()方法调用的私有方法,我将输入文件路径作为参数传递给该私有方法。我的待测试代码是main()方法。在private方法中间的某个位置,将读取文件并执行一些操作。

我如何:

1。通过字符串类型(“ src / test / resources / test.txt”)的文件路径作为参数。如果传递文件路径,则得到FileNotFoundException

2。如何在找不到文件的情况下测试以私有方法处理的IOException?

在此处添加我的代码段:

被测代码:

public class MyApp {

    public static void main(String[] args) {
        new MyApp().readFile(args);
    }

    private void readFile(String[] args) {
        if (args != null) {
            String file = args[0];
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    // More business logic here for processing that line
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

主测试:

    @Test
    void mainTest() {
        String[] args = {"/test_input.txt"};
        MyApp.main(args);
        assertNotNull(<some_object_after_processing>);
    }
java unit-testing junit junit4 junit5
2个回答
0
投票

要获取文件路径,您可以在this link中使用适当的方式无需检查main方法的任何断言。如果测试用例成功完成,则通过。


0
投票

感谢您提出疑问!首先,您需要更改应用程序代码,因为要从args [0]位置读取单个文件,然后再读取字符串数组[File Array或files collection]。

1]在您的项目中创建“资源”文件夹:

右键单击项目并创建一个名称为'resources'的文件夹。

2]在“资源”文件夹中创建“ test.txt”。

3]修改后的代码:

package com.application;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class MyApp {

    public static void main(String[] args) {
        new MyApp().readFile("resources/Test.txt");
    }
    private void readFile(String fileName) {
        if (fileName != null) {

            try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    // More business logic here for processing that line
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }
}

这里,您可以将fileName直接传递给方法。希望它能帮助您解决第一个查询。

© www.soinside.com 2019 - 2024. All rights reserved.