'我有多个用户输入提示,是否可以形成一个用户输入列表,并让它在时间到来时提取相应的输入?'
@Test
public void test1() {
String simulatedUserInput = "1n"+"2n"+"3n" ;
InputStream savedStandardInputStream = System.in;
System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes()));
// code that needs multiple user inputs
System.setIn(savedStandardInputStream);
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
String[] args = {} ;
Demo.main(args);
String consoleOutPutString ="Enter side 1: "+ System.getProperty("line.separator")+"1"+ System.getProperty("line.separator");
consoleOutPutString +="Enter side 2: "+ System.getProperty("line.separator")+"2"+ System.getProperty("line.separator");
consoleOutPutString +="Enter side 3: "+ System.getProperty("line.separator")+"3"+ System.getProperty("line.separator");
consoleOutPutString +="This is not a triangle."+ System.getProperty("line.separator");
assertEquals(consoleOutPutString, out.toString());
}
}
"此代码不起作用">
在此处输入图像描述
您可以使用term4j:包装System.in
public static void main(String[] args) {
new YourApp(
new Stdin(), // Stdin is a wrapper for Scanner.in
new Stdout() // Stdout is a wrapper for System.out
).start(args);
}
这是Stdin
的单元测试
@Test
public void readFromStdin() {
/**
* The standard system input (stdin) which keeps the expected input lines in-memory
* instead of direct manipulations with {@link System#in} or {@link Console}.
*/
final Input stdin = new Stdin(
new InputOf(String.format("line1%nline2"))
);
MatcherAssert.assertThat(
"The 1st line was read from console",
stdin.value(),
new IsEqual("line1")
);
MatcherAssert.assertThat(
"The 2nd line was read from console",
stdin.value(),
new IsEqual("line2")
);
}
这是Stdout
的单元测试
/**
* Simulate the STD print procedure using {@link StringWriter}.
*/
@Test
public void printToWriter() {
// Write 4 lines delimited by `n` or `rn` to the StringWriter
final StringWriter swter = new StringWriter();
final Output std = new Stdout(swter);
std.print("line1", "line2");
std.print("line3", "line4");
// Check that the result string has 4 lines
MatcherAssert.assertThat(
"4 lines of text were printed to the output",
swter.toString(),
new HasLines("line1", "line2", "line3", "line4")
);
}
对于您的情况,您可以使用以下代码在测试中模拟System.in
和System.out
:
public class YourAppTest {
@Test
public void skeleton(){
Input stdin = new Stdin(
new InputOf(String.format("line1%nline2")) // expected multiple user input from terminal
);
StringWriter stdout = new StringWriter(); // the app output to terminal
new YourApp(stdin, new Stdout(stdout))
.start(...);
MatcherAssert.assertThat(
"4 lines of text were printed to the output",
out.toString(),
new HasLines("line1", "line2", "line3", "line4")
);
}
}