1

私はJUnitとユニットテストに非常に慣れていないため、スキャナーオブジェクトへのユーザー入力のモックについて質問があります。テストしたい次のコードがあります。非常に基本的です。

コードを実行

import java.util.Scanner;

public class MyGame{
    public MyGame() {
        Scanner response = new Scanner(System.in);

        int game;

        System.out.println("Enter a game.");
        System.out.println("Press 1 for Super Awesome Bros.");
        System.out.println("Press 2 for a Random game.");

        game = response.nextInt();

        if (game == 1){
            System.out.println("Super Awesome Bros.");
    }
  }
}

これが私のテストケースです

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.contrib.java.lang.system.StandardOutputStreamLog;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.*;

@RunWith(JUnit4.class)
    public class Testsuite {

      @Rule
      public final StandardOutputStreamLog out = new StandardOutputStreamLog();

      @Rule
      public final TextFromStandardInputStream in = emptyStandardInputStream();

  @Test
  public void printOutput() {
    in.provideText("1\n");
    new MyGame();
    assertThat(out.getLog(), containsString("Super Awesome Bros."));
  }

}

したがって、私のテストケースでは、期待される出力を受け取ることができるように、入力を 1 にモックしようとしています。しかし、何らかの理由で、出力が何であるかに関係なく、私のコードは合格します。何が間違っているのかわかりません。出力が期待どおりでない場合、テストは失敗するはずです。誰かが問題を見つけることができますか? 繰り返しますが、私は JUnit とユニット テストを理解しようとしています。私は主にPythonでテストすることに慣れています。上級者の皆様、ありがとうございました。

4

1 に答える 1