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

Java 如何为JUnit模拟多用户输入,java,junit,Java,Junit,现在我有这个 ByteArrayInputStream in = new ByteArrayInputStream("2".getBytes()); System.setIn(in); //code that does something with user inputs 但问题是,在//代码中,我有多个用户输入提示,是否可以形成一个用户输入列表,并在时机成熟时让它拾取相应的输入?我尝试过做一些愚蠢的事情,比如“2\n2\n10\nHello\n”.getBytes(),但没有成功 编辑:

现在我有这个

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

//code that does something with user inputs
但问题是,在//代码中,我有多个用户输入提示,是否可以形成一个用户输入列表,并在时机成熟时让它拾取相应的输入?我尝试过做一些愚蠢的事情,比如“2\n2\n10\nHello\n”.getBytes(),但没有成功

编辑:

我正在使用扫描仪对象获取用户输入:

Scanner inputScanner = new Scanner(System.in);
inputScanner.nextLine();
您可以这样做:

  • 用模拟输入加上延迟时间构建一个
    DelayQueue

  • 在调用read()时,通过tarrayinputstream扩展
    并重写
    read()
    方法来读取
    DelayQueue

  • 编辑:示例代码(未完全实现-上午在电话会议上)

    公共类DelayedString实现延迟{
    私人最终长延迟单位为毫秒;
    私有最终字符串内容;
    公共延迟字符串(长延迟,字符串内容){
    this.delayInMillis=延迟;
    this.content=内容;
    }
    公共字符串getContent(){
    返回内容;
    }
    公共长getDelay(时间单位时间单位){
    返回TimeUnit.millises.convert(delayInMillis,TimeUnit);
    }
    }
    公共类MyInputStream实现InputStream{
    专用ByteBuffer缓冲区=ByteBuffer.allocate(8192);
    私有最终延迟队列;
    公共MyInputStream(延迟队列){
    this.queue=队列;
    }
    公共int read(){
    updateBuffer();
    如果(!buffer.isEmpty()){
    //在缓冲区内交付内容
    }
    }
    公共整型读取(字符[]缓冲区,整型计数){
    updateBuffer();
    //将字节缓冲区中的内容传递到缓冲区
    }
    受保护的void updateBuffer(){
    for(DelayedString s=queue.peek();s!=null;){
    if(buffer.capacity()>buffer.limit()+s.getContent().length()){
    s=queue.poll();
    append(s.getContent());
    }否则{
    打破
    }
    }
    }
    }
    
    仅使用“新行”就足够了

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

    关于如何获得用户输入的详细信息-显示代码?@AndersR.Bystrup编辑的问题嗯,你能给我一个小例子吗?我不完全确定该怎么做。
    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);