如何为JUnit模拟多个用户输入

7

现在我有这个

ByteArrayInputStream in = new ByteArrayInputStream("2".getBytes());
System.setIn(in);

//code that does something with user inputs

但问题在于,我有多个用户输入提示的 //代码中,是否可以形成一个用户输入列表,并在需要时获取相应的输入?我尝试过一些愚蠢的事情,比如“2\n2\n10\nHello\n”.getBytes(),但那行不通。
编辑:
我正在使用Scanner对象获取用户输入:
Scanner inputScanner = new Scanner(System.in);
inputScanner.nextLine();

如何获取用户输入的详细信息 - 显示代码? - Anders R. Bystrup
@AndersR.Bystrup编辑了问题。 - Stupid.Fat.Cat
2个回答

7
只需要使用“换行”即可。
String simulatedUserInput = "input1" + System.getProperty("line.separator")
    + "input2" + System.getProperty("line.separator");

InputStream savedStandardInputStream = System.in;
System.setIn(new ByteArrayInputStream(simulatedUserInput.getBytes()));

// code that needs multiple user inputs

System.setIn(savedStandardInputStream);

2
你可以这样做:
  1. 使用模拟输入和延迟时间构建一个 DelayQueue

  2. 扩展 BytArrayInputStream 并重写 read() 方法,在调用时读取 DelayQueue

编辑:示例代码(未完全实现 - 正在进行电话会议)

public class DelayedString implements Delayed {

    private final long delayInMillis;

    private final String content;

    public DelayedString(long delay, String content) {
        this.delayInMillis = delay;
        this.content = content;
    }

    public String getContent() {
        return content;
    }

    public long getDelay(TimeUnit timeUnit) {
        return TimeUnit.MILLISECONDS.convert(delayInMillis, timeUnit);
    }
}

public class MyInputStream implements InputStream {

    private ByteBuffer buffer = ByteBuffer.allocate(8192);

    private final DelayQueue<DelayString> queue;

    public MyInputStream(DelayQueue<DelayString> queue) {
        this.queue = queue;
    }

     public int read() {
         updateBuffer();
         if (!buffer.isEmpty()) {
            // deliver content inside buffer
         }
     }

     public int read(char[] buffer, int count) {
         updateBuffer();
         // deliver content in byte buffer into buffer
     }

     protected void updateBuffer() {
         for (DelayedString s = queue.peek(); s != null; ) {
             if (buffer.capacity() > buffer.limit() + s.getContent().length()) {
                 s = queue.poll();
                 buffer.append(s.getContent());
             } else {
                 break;
             }
         }
     }
}

嗯,你能给我一个小例子吗?我不太确定该怎么做。 - Stupid.Fat.Cat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接