parent
c9637e95fd
commit
3eeb5c7d2b
|
@ -0,0 +1,27 @@
|
|||
package com.baeldung.userinput;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class UserInputHandler {
|
||||
|
||||
public static List<String> readUserInput() {
|
||||
List<String> userData = new ArrayList<>();
|
||||
System.out.println("Please enter your data below: (send 'bye' to exit) ");
|
||||
Scanner input = new Scanner(System.in);
|
||||
while (true) {
|
||||
String line = input.nextLine();
|
||||
if ("bye".equalsIgnoreCase(line)) {
|
||||
break;
|
||||
}
|
||||
userData.add(line);
|
||||
}
|
||||
return userData;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<String> userData = readUserInput();
|
||||
System.out.printf("User Input Data:\n%s", String.join("\n", userData));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,36 @@
|
|||
package com.baeldung.userinput;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class UserInputHandlerUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenDataInSystemIn_whenCallingReadUserInputMethod_thenHaveUserInputData() {
|
||||
String[] inputLines = new String[]{
|
||||
"The first line.",
|
||||
"The second line.",
|
||||
"The last line.",
|
||||
"bye",
|
||||
"anything after 'bye' will be ignored"
|
||||
};
|
||||
String[] expectedLines = Arrays.copyOf(inputLines, inputLines.length - 2);
|
||||
List<String> expected = Arrays.stream(expectedLines).collect(Collectors.toList());
|
||||
InputStream stdin = System.in;
|
||||
try {
|
||||
System.setIn(new ByteArrayInputStream(String.join("\n", inputLines).getBytes()));
|
||||
List<String> actual = UserInputHandler.readUserInput();
|
||||
assertThat(actual).isEqualTo(expected);
|
||||
} finally {
|
||||
System.setIn(stdin);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue