2014-05-14 9 views
5

Teraz mam toJak symulować Multiple Input użytkownika dla JUnit

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

//code that does something with user inputs 

Ale problemem jest to, że w // kod, który robi coś mam Multiple Input wydawania poleceń, jest to możliwe, aby utworzyć listę wejście użytkownika i czy odbierze odpowiednie wejście, gdy nadejdzie czas? Próbowałem robić głupie rzeczy takie jak "2 \ n2 \ n10 \ nHello \ n" .getBytes(), ale to nie zadziałało.

EDIT:

jestem coraz moje dane wejściowe użytkownika z obiektem Scanner:

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

Szczegółowe informacje na temat uzyskiwania danych wejściowych użytkownika - pokaż kod? –

+0

@ AndersR.Bystrup edytowane pytanie –

Odpowiedz

2

Wystarczy za pomocą "nowej linii" powinno wystarczyć.

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

Można zrobić tak:

  1. Narysuj DelayQueue z symulowanego wejścia plus Czas zwłoki.

  2. Poszerzanie BytArrayInputStream i przesłonięcie metody read(), aby odczytać DelayQueue podczas wywoływania read().

EDIT: przykładowy kod (nie w pełni wdrożone - jestem na spotkaniu tel)

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

Hmm, czy mógłbyś podać mi mały przykład do pracy? Nie do końca pewna, jak to osiągnąć. –

+0

Jest to o wiele bardziej skomplikowane, niż sądziłem, hah ... –