2

I wrote a test in junit 5, I test the user input in the terminal, but I have the error "java.util.NoSuchElementException".

I want to test user input in the terminal.

//GIVEN
System.setIn(new ByteArrayInputStream("5\n1\n1\n1\n1\n1\n1\n1\n1\n1\n".getBytes()));
createPlayer();
GameScore gameScore = new GameScore(players);
gameScore.score();
//WHEN
String[] output = outContent.toString().replace("\r\n", "\n").split("\n");
//THEN
assertEquals("Veuillez choisir entre l'attaque basic ou special (1-2)", output[2]);
public int intReader(int min, int max, String errorMessage){
    int inputRead = -1;
    do{
        try{
            inputRead = sc.nextInt();
            responseIsGood = (inputRead >= min && inputRead <= max);
        }catch (InputMismatchException e){
            sc.next();
            responseIsGood = false;
        }
            if (!responseIsGood) System.out.println(errorMessage);
    }while (!responseIsGood);

    return inputRead;
}
java.util.NoSuchElementException
    at java.base/java.util.Scanner.throwFor(Scanner.java:937)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at com.magicworld.interaction.InputReader.intReader(InputReader.java:21)
    at com.magicworld.interaction.GameScore.score(GameScore.java:36)    
yole
  • 92,896
  • 20
  • 260
  • 197
krimo
  • 21
  • 4
  • the problem was in the loop in the method gameScore.score(), it waits 20 entered user and not 9. **System.setIn(new ByteArrayInputStream("5\n1\n1\n1\n1\n1\n1\n1\n1\n1\n".getBytes()));** The correct System.setIn is with 20 entry System.setIn(new **ByteArrayInputStream("3\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n".getBytes()));** – krimo May 07 '19 at 10:12

0 Answers0