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

时间:2014-05-14 11:48:38

标签: java junit

现在我有了这个

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

//code that does something with user inputs

但问题是,在//代码执行的操作中,我有多个用户输入提示,是否可以形成用户输入列表并在时机到来时获取相应的输入?我尝试过像#34; 2 \ n2 \ n10 \ nHello \ n" .getBytes()这样的愚蠢的事情,但这并没有奏效。

编辑:

我通过Scanner对象获取用户输入:

Scanner inputScanner = new Scanner(System.in);
inputScanner.nextLine();

2 个答案:

答案 0 :(得分:2)

你可以这样做:

  1. 使用模拟输入和延迟时间构建DelayQueue

  2. 在调用read()时,扩展BytArrayInputStream并覆盖read()方法以读取DelayQueue

  3. 编辑:示例代码(未完全实施 - 我在电话会议上)

    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;
                 }
             }
         }
    }
    

答案 1 :(得分:2)

只需使用“新行”即可。

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);