如何对扫描仪进行单元测试 请帮助我不明白

How to Unit test a Scanner Pls help i dont get it

我不太擅长编程yet.My学习任务是单元测试和编程策划。我已经完成了所有测试,但我真的坚持用扫描仪测试一种方法。我知道模拟和一切,但我没有找到如何模拟 Inputstream 或某种 ByteArray 的解决方案。如果我总是测试它,结果会阻止我并等待控制台进入,所以测试不会过去。方法代码如下:

public String[] guess(){ //Eingabe vom Raten des ersten Versuchs in !!!STRINGS!!!
        int k = 1;
        Scanner valueIn = new Scanner(System.in);
        String[] guess = new String[4];
        for(int i = 0; i < 4;i++){
            k = 1;
            while(k==1) {
                System.out.println("now the " + (i + 1) + "color ");
                guess[i] = valueIn.nextLine();
                if(guess[i].equals("red")||guess[i].equals("blue")||guess[i].equals("yellow")||guess[i].equals("green")||guess[i].equals("purple")||guess[i].equals("brown")){
                    k = 0;
                }
            }
        }
        return guess;
    }

有人能帮我吗,我真的在哭;(。请提供完整的结果或完整的详细解决方案

使用 System.setIn() 方法。

@Test
public void test(){
    String[] expectedOutputArray = {"red", "green", "yellow", "brown"};
    String input = "red\ngreen\nyellow\nbrown";
    InputStream in = new ByteArrayInputStream(input.getBytes());
    System.setIn(in);
    String[] outputArray = guess(); //call your guess function
    Assert.assertArrayEquals(expectedOutputArray, outputArray);
}
  • System.in 基本上是一个从控制台读取的 InputStream(因此您在控制台中输入)。
  • 所以准备一个InputStream,设置为in属性 of System class,使用 System.setIn(in)

我正在采用另一种方法来重新格式化代码以测试猜测方法,从而消除对 System.in

的依赖

请将每个 class, 放在不同的 java 文件中

public class GuessRefactor {
    private SystemClass systemObj;

    public String[] guess(SystemClass systemObj){
        int k = 1;
        String[] guess = new String[4];
        for(int i = 0; i < 4;i++){
            k = 1;
            while(k==1) {
                System.out.println("now the " + (i + 1) + "color ");
                guess[i] = systemObj.getInput();
                if(guess[i].equals("red")||guess[i].equals("blue")||guess[i].equals("yellow")||guess[i].equals("green")||guess[i].equals("purple")||guess[i].equals("brown")){
                    k = 0;
                }
            }
        }
        return guess;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new GuessRefactor().guess(new SystemClass())));
    }
}


public class SystemClass {
    Scanner valueIn = new Scanner(System.in);

    public String getInput(){
        return valueIn.nextLine();
    }
}


@RunWith(MockitoJUnitRunner.class)
public class TestClass {
    @Mock
    SystemClass systemClass;

    @Test
    public void test(){
        GuessRefactor guessRefactor = new GuessRefactor();
        Mockito.when(systemClass.getInput()).thenReturn("red");
        String[] expectedOutput = {"red", "red", "red", "red",};
        String[] output = guessRefactor.guess(systemClass);
        Assert.assertArrayEquals(expectedOutput, output);
    }
}