How can I unit test a method that uses a Scanner and an InputStream?
So here is the code:
public int foo(InputStream in) {
int counter = 0;
Scanner scanner = new Scanner(in);
while(scanner.hasNextLine()) {
counter++;
scanner.nextLine();
}
return counter;
}
Normally I will be passing a FileInputStream to this method, however I want to be able to test it without accessing a physical file.
Should I mock the File object? How to I implement
@Test
public void shouldReturnThree(){
}
You can pass a test String into the method as an InputStream like this (:
InputStream stream = new ByteArrayInputStream(exampleString.getBytes());
(Shamelessly stolen from this answer)
For instance, this code will print 3:
String str = "nnn";
InputStream stream = new ByteArrayInputStream(str.getBytes());
System.out.println(foo(stream));
链接地址: http://www.djcxy.com/p/78468.html