Java 使用Junit模拟用户对Scanner对象的输入
我对JUnit和单元测试非常陌生,对于模拟用户输入到Scanner对象有一个问题。我有以下代码要测试。非常基本 运行代码Java 使用Junit模拟用户对Scanner对象的输入,java,unit-testing,junit,system-rules,Java,Unit Testing,Junit,System Rules,我对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.");
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进行测试。感谢advanced中的每个人。您的测试总是通过的,因为您总是在编写字符串“Press 1 for Super Aesome Bros.”。因此支票
assertThat(out.getLog(), containsString("Super Awesome Bros."));
比赛总是如此
顺便说一下,您不必编写
@RunWith(JUnit4.class)
。您可以删除该行。您的测试始终通过,因为您总是在编写字符串“Press 1 for Super Awesome Bros.”。因此支票
assertThat(out.getLog(), containsString("Super Awesome Bros."));
比赛总是如此
顺便说一下,您不必编写
@RunWith(JUnit4.class)
。您可以删除该行。Install,右键单击测试名称并选择“Debug”,然后您将能够跟踪执行并轻松找到失败/成功的原因。如果不确定如何进行调试,请阅读有关调试的内容:如果将.providext(“2\n”)中的测试第一行更改为,是否意味着测试仍然是绿色的代码>?如何运行测试?我认为System.out实际上会在以下行中接收到文本Super Awesome Bros.:System.out.println(“按1表示Super Awesome Bros.”;,所以测试总是会通过的。在类中硬连接对系统的依赖性是一个好主意吗?我更愿意通过构造函数提供一个输入流,这样测试代码就可以使用ByteArrayInputStream
或其他东西。安装时,右键单击测试名称并选择“Debug”,然后您就可以跟踪执行并轻松找出失败/成功的原因。如果不确定如何进行调试,请阅读有关调试的内容:如果将.providext(“2\n”)中的测试第一行更改为,是否意味着测试仍然是绿色的代码>?如何运行测试?我认为System.out实际上会在以下行中接收到文本Super Awesome Bros.:System.out.println(“按1表示Super Awesome Bros.”;,所以测试总是会通过的。在类中硬连接对系统的依赖性是一个好主意吗?我更愿意通过构造函数提供一个输入流,这样测试代码就可以使用ByteArrayInputStream
之类的东西。