java - Unit testing multiple consecutive keyboard inputs -
i'm trying unit test main method takes input keyboard. know there several questions on testing keyboard input , use of system.setin(...) so, works first input me.
my code:
public class testapp { @test public void testmain() { inputstream stdin = system.in; try { system.setin(new bytearrayinputstream("s\r\nx\r\n".getbytes())); string args[] = {}; app.main(args); // todo: verify output expected } catch(ioexception e) { asserttrue("unexpected exception thrown: " + e.getmessage(), false); } { system.setin(stdin); } } } what i'm trying achieve input 's' , 'x' (two different entries).
when using program normally, should output stuff after pressing 's' followed enter key, , output else after pressing 'x'. main method looks this:
class app { public static void main(string[] args) throws ioexception { int choice; { choice = getchar(); switch(choice) { case 's': system.out.println("text s"); break; case 'x': system.out.println("exiting"); break; } } while(choice != 'x'); } public static string getstring() throws ioexception { inputstreamreader isr = new inputstreamreader(system.in); bufferedreader br = new bufferedreader(isr); string s = br.readline(); return s; } public static char getchar() throws ioexception { string s = getstring(); return s.charat(0); } } note: know best way achieve inject inputstream dependency , use instead of system.in, can't change code. restriction have, can't change main(), getstring() or getchar() methods.
when execute test, output:
text s
java.lang.nullpointerexception
@ app.getchar(tree.java:28)
@ app.main(tree.java:7)
@ testapp.testmain(testapp.java:15) <23 internal calls>
so, looks gets first input ('s'), not second one...
any appreciated.
the getstring method constructs new bufferedreader on each call, read 8192 characters system.in buffer before readline returns. means it's reading 's' 'x' on first call, using first line. then, on return method, bufferedreader discarded. on next call constructs new instance remaining characters but, system.in drained, finds none.
it goes without saying that's bug.
one possible workaround construct dummy inputstream, padding 8k mark after initial 's' , newline followed 'x' , newline.
you construct more elaborate mock system.in coupled mock system.out , replenish more input when detect call system.out.println.
Comments
Post a Comment