Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate multiple user input for JUnit

Tags:

java

junit

Right now I have this

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

//code that does something with user inputs

But the issue is that in //code that does something I have multiple user input prompts, is it possible to form a list of the user input and have it pick up the corresponding input when the time comes? I tried doing silly things like "2\n2\n10\nHello\n".getBytes() but that didn't work.

EDIT:

I am getting my user input with a Scanner object:

Scanner inputScanner = new Scanner(System.in);
inputScanner.nextLine();
like image 540
Stupid.Fat.Cat Avatar asked May 14 '14 11:05

Stupid.Fat.Cat


2 Answers

Just using a "new line" should be enough.

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);
like image 98
user1660514 Avatar answered Oct 27 '22 21:10

user1660514


You can do like this:

  1. Construct a DelayQueue with your simulated input plus the delay time.

  2. Extend the BytArrayInputStream and override the read() method to read a DelayQueue when read() is called.

EDIT: sample code (not fully implemented - am on a tel meeting)

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;
             }
         }
     }
}
like image 22
Alex Suo Avatar answered Oct 27 '22 21:10

Alex Suo