1

我对 JUnit 和单元测试非常陌生,并且对模拟用户对 Scanner 对象的输入有疑问。我有以下要测试的代码。非常基本。

运行代码

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

0

Your test is always passing because you're always writing the String "Press 1 for Super Awesome Bros.". Therefore the check

assertThat(out.getLog(), containsString("Super Awesome Bros."));

matches always.

By the way you don't have to write @RunWith(JUnit4.class). You can remove that line.

于 2017-01-26T00:18:21.163 回答