问题描述
我必须在类中测试一个使用Scanner类输入的方法。
I have to test a method in a class which takes an input using Scanner class.
package com.math.calculator;
import java.util.Scanner;
public class InputOutput {
public String getInput() {
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
}
我想用JUnit测试它但不确定如何要做到这一点。
I want to test it using JUnit but not sure how to do it.
我尝试使用以下代码,但它无法正常工作。
I tried using the following code but it wont work.
package com.math.calculator;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class InputOutputTest {
@Test
public void shouldTakeUserInput() {
InputOutput inputOutput= new InputOutput();
assertEquals("add 5", inputOutput.getInput());
}
}
我想和Mockito一起尝试(使用mock ......当......然后返回)但不知道该怎么做。
I want to also try it with Mockito (using mock... when ... thenReturn) but not sure how to do it.
推荐答案
你可以改变 System.in
使用 System.setIn()
方法流。
You can change the System.in
stream using System.setIn()
method.
尝试这个,
@Test
public void shouldTakeUserInput() {
InputOutput inputOutput= new InputOutput();
String input = "add 5";
InputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
assertEquals("add 5", inputOutput.getInput());
}
您刚刚修改了 System.in
字段。 System.in
基本上是 InputStream
,它从控制台读取
(因此您在控制台中输入)。但是你只是修改了它,让系统从提供的输入流
中读取。所以它不再从控制台读取,而是从提供的输入流中读取。
You have just modified the System.in
field. System.in
is basically an InputStream
which reads from the console
(hence your input in the console). But you just modified it and let the system to read from the provided inputstream
instead. So it wont read from console anymore but from the inputstream provided.
这篇关于使用Scanner对用户输入进行junit测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!