I am working on unit testing a Java application, and I am facing an issue with handling System.in for testing exception scenarios. My tests are designed to check if the application throws the correct exception when invalid input is provided.
Here is the code for initializing and restoring the System.in stream, and a couple of test cases:
public class RacingGameTest {
private InputStream originalInputStream = System.in;
void initializeStreams(String inputKey) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(inputKey.getBytes());
System.setIn(byteArrayInputStream);
}
@AfterEach
void restoreStreams() {
System.setIn(originalInputStream);
}
@Test
void 입력이_공백일_때_IllegalBlankException_던지기() {
// Given
final String ONLY_BLANK = " ";
// When
initializeStreams(ONLY_BLANK);
// Then
Assertions.assertThatThrownBy(racingGame::start).isInstanceOf(IllegalBlankException.class);
}
@Test
void 이름이_누락되었을_때_IllegalBlankException_던지기() {
// Given
final String STRING_NAMES_CONTAIN_SPACE = "name1, ,name3";
// When
initializeStreams(STRING_NAMES_CONTAIN_SPACE);
// Then
Assertions.assertThatThrownBy(racingGame::start).isInstanceOf(IllegalBlankException.class);
}
}
In the first test, I am checking if IllegalBlankException is thrown when the input is a blank string. In the second test, I am verifying if IllegalBlankException is thrown when a name is missing.
When I run these tests individually, they pass. However, when I run all the tests in the class together, I face issues with System.in not being reset properly, resulting in java.util.NoSuchElementException: No line found for tests that run after the first one.
I have used @AfterEach to restore System.in after each test, but it seems like it's not working as expected. Am I missing something? How can I ensure that System.in is properly reset after each test?