簡體   English   中英

使用Scanner和System.in(Java)進行方法的Junit測試

[英]Junit test of method with Scanner and System.in (Java)

我是編程的新手,我有一個簡單的方法:

public double input() {
        double result = 0;
        Scanner scanner = new Scanner(System.in);
        if (scanner.hasNextDouble()) {
            result = scanner.nextDouble();
        } else {
            System.out.print("Please, type numbers!\n");
        }
        return result;
    }

問題是在junit測試中如何從鍵盤模擬(模擬)用戶輸入。

Scanner作為輸入參數傳遞到要測試的方法。 在測試代​​碼中,您可以從字符串創建Scanner實例:

Scanner scanner = new Scanner("the sample user input");

然后在生產代碼中,可以將new Scanner(System.in)傳遞給該方法。

您應該閱讀有關依賴注入的更多信息。

您的班級不應與其他班級緊密結合。 可以根據需要向多個級別的對象提供依賴項。

  1. 如果是字段,則使用構造函數/設置器。
  2. 如果范圍僅在方法中,則使用方法參數。

就您而言,只要您說:-

Scanner scanner = new Scanner(System.in);

現在,您的代碼已與System.in流完全耦合。 相反,您應該以以下格式將其作為方法的參數注入。

public double input(InputStream inputStream) {
    double result = 0;
    Scanner scanner = new Scanner(inputStream);
    if (scanner.hasNextDouble()) {
        result = scanner.nextDouble();
    } else {
        System.out.print("Please, type numbers!\n");
    }
    return result;
}

現在,可以從您的主要代碼中使用System.in進行調用。 在測試類中,可以使用任何InputStream調用它。 通常,我們為此使用mock/stub

注意:-上面只是一個示例,可以根據需要進行更改。

暫無
暫無

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

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