簡體   English   中英

通過在私有方法中傳遞文件路徑字符串和 IOException 處理來進行 Junit 測試

[英]Junit test by passing file path string and IOException handling inside private method

我有一個從 main() 方法調用的私有方法,我將輸入文件路徑作為參數傳遞給該方法。 我的被​​測代碼是 main() 方法。 在私有方法中間的某個地方,讀取文件並執行一些操作。

我怎樣才能:

1.傳遞String類型的文件路徑(“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>);
    }

要獲取文件路徑,您可以在此鏈接中使用合適的方式
不需要檢查main方法的任何斷言。 如果測試用例成功完成,那么它就通過了。

感謝您提出疑問! 首先,您需要更改應用程序代碼,因為您正在從 args[0] 位置讀取單個文件,那么為什么要讀取字符串數組 [文件數組或文件集合]。

1]在您的項目中創建“資源”文件夾:

右鍵單擊項目並創建一個名為“資源”的文件夾。

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();
            }
        }
    }
}

在這里,您可以將文件名直接傳遞給方法。 我希望它能幫助您解決您的第一個查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM