我正在创建 JUnit 并测试以下方法:
public static String readLine() throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
return stdin.readLine();
}
我想提前在JUnit测试方法中制作输入字符串,而不是在readLine()中通过自己在控制台获取inputput来制作输入字符串。
我怎样才能做到这一点?
最佳答案
您可以使用 Mockito 之类的东西来模拟输入流。但没有这个也可以完成。使用 System.setIn()
您可以更改 System.in
将返回的流。
public class ReaderTest {
@Test
public void test() throws IOException {
String example = "some input line"; //the line we will try to read
InputStream stream = new ByteArrayInputStream((example+"\n").getBytes(StandardCharsets.UTF_8)); //this stream will output the example string
InputStream stdin = System.in; //save the standard in to restore it later
System.setIn(stream); //set the standard in to the mocked stream
assertEquals(example, Reader.readLine()); //check if the method works
System.setIn(stdin);//restore the stardard in
}
}
class Reader{
public static String readLine() throws IOException{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
return stdin.readLine();
}
}
模拟流的另一个优点是您不必在每次想要运行测试时都输入字符串。
另请注意,如果您打算经常执行此操作,则可以在 before 和 after 方法中恢复 System.in
。
关于java - 在 JUnit 测试中提前获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44471683/