Junit test Scanner input issue The Next CEO of Stack OverflowJUnit: How to simulate System.in testing?Scanner cannot be resolved to a typeHow do you assert that a certain exception is thrown in JUnit 4 tests?JUnit test for System.out.println()Scanner vs. BufferedReaderHow to run test methods in specific order in JUnit4?Maven does not find JUnit tests to runScanner is skipping nextLine() after using next() or nextFoo()?Getting a NoSuchElementsException in Java?I/P-a string S.O/P: For each digit start from 0-9,print count of their occurrence in S.Print10 lines,each line contain 2 space separated integersWould it make any difference giving arguments using scanner class instead of command line arguments?

Does higher Oxidation/ reduction potential translate to higher energy storage in battery?

Is a distribution that is normal, but highly skewed, considered Gaussian?

Players Circumventing the limitations of Wish

"Eavesdropping" vs "Listen in on"

From jafe to El-Guest

What would be the main consequences for a country leaving the WTO?

Purpose of level-shifter with same in and out voltages

Which Pokemon have a special animation when running with them out of their pokeball?

Why did early computer designers eschew integers?

Help! I cannot understand this game’s notations!

Point distance program written without a framework

Is there an equivalent of cd - for cp or mv

In the "Harry Potter and the Order of the Phoenix" video game, what potion is used to sabotage Umbridge's speakers?

How to get the last not-null value in an ordered column of a huge table?

Where do students learn to solve polynomial equations these days?

Do scriptures give a method to recognize a truly self-realized person/jivanmukta?

Is there a difference between "Fahrstuhl" and "Aufzug"?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Why do we say 'Un seul M' and not 'Une seule M' even though M is a "consonne"

Traveling with my 5 year old daughter (as the father) without the mother from Germany to Mexico

What are the unusually-enlarged wing sections on this P-38 Lightning?

Small nick on power cord from an electric alarm clock, and copper wiring exposed but intact

IC has pull-down resistors on SMBus lines?

Does Germany produce more waste than the US?



Junit test Scanner input issue



The Next CEO of Stack OverflowJUnit: How to simulate System.in testing?Scanner cannot be resolved to a typeHow do you assert that a certain exception is thrown in JUnit 4 tests?JUnit test for System.out.println()Scanner vs. BufferedReaderHow to run test methods in specific order in JUnit4?Maven does not find JUnit tests to runScanner is skipping nextLine() after using next() or nextFoo()?Getting a NoSuchElementsException in Java?I/P-a string S.O/P: For each digit start from 0-9,print count of their occurrence in S.Print10 lines,each line contain 2 space separated integersWould it make any difference giving arguments using scanner class instead of command line arguments?










0















I am currently trying to Junit test a game for a Uni assignment. Below is an example of the kind of methods I am trying to test.



public static int choosePlayers(int num) 
while (validPlayerNumber == false)
try
System.out.print("Please enter Number of players (2-4)n> ");
num = in.nextInt();
switch (num)
case 2:
validPlayerNumber = true;
numberPlayers = num;
System.out.println(numberPlayers + " players selected");
break;
case 3:
validPlayerNumber = true;
numberPlayers = num;
System.out.println(numberPlayers + " players selected");
break;
case 4:
validPlayerNumber = true;
numberPlayers = num;
System.out.println(numberPlayers + " players selected");
break;
default:
throw new IllegalArgumentException("Sorry, that is not a valid selection.");
// System.out.println("Sorry, that is not a valid selection.");

catch (InputMismatchException ex)
// log the exception
System.out.println("Problem with input : " + ex.toString());
continue;


return numberPlayers;



I am using the following test class to test this:



/**
* @throws java.lang.Exception
*/
@Before

public void setUp() throws Exception
num1 =1;
num2= 2;
num4 = 4;
num3 = 3;
num5 = 5;
game= new Game();


@Test
public void testchoosePlayers2()

System.out.println("Testing choosingPlayers 2");
Scanner scanner = new Scanner (System.in);
int expected = scanner.nextInt();
int actual = game.choosePlayers(num2);
assertEquals(expected, actual);
System.out.println("Test finsihed");



@Test
public void testchoosePlayers3()
System.out.println("Testing choosingPlayers 3");
Scanner scanner = new Scanner (System.in);
int expected = scanner.nextInt();
int actual = game.choosePlayers(num3);
assertEquals(expected, actual);
System.out.println("Test finsihed");




@Test
public void testchoosePlayers4()
System.out.println("Testing choosingPlayers 4");
Scanner scanner = new Scanner (System.in);
int expected = scanner.nextInt();
int actual = game.choosePlayers(num4);
assertEquals(expected, actual);
System.out.println("Test finsihed");




Every time I try and run this test only the first test will run and the scanner is not re-prompted for the subsequent 2. Is there any way around this? I would greatly appreciate any advice concerning this issue or for a better/more efficient way to test the above method .










share|improve this question


























    0















    I am currently trying to Junit test a game for a Uni assignment. Below is an example of the kind of methods I am trying to test.



    public static int choosePlayers(int num) 
    while (validPlayerNumber == false)
    try
    System.out.print("Please enter Number of players (2-4)n> ");
    num = in.nextInt();
    switch (num)
    case 2:
    validPlayerNumber = true;
    numberPlayers = num;
    System.out.println(numberPlayers + " players selected");
    break;
    case 3:
    validPlayerNumber = true;
    numberPlayers = num;
    System.out.println(numberPlayers + " players selected");
    break;
    case 4:
    validPlayerNumber = true;
    numberPlayers = num;
    System.out.println(numberPlayers + " players selected");
    break;
    default:
    throw new IllegalArgumentException("Sorry, that is not a valid selection.");
    // System.out.println("Sorry, that is not a valid selection.");

    catch (InputMismatchException ex)
    // log the exception
    System.out.println("Problem with input : " + ex.toString());
    continue;


    return numberPlayers;



    I am using the following test class to test this:



    /**
    * @throws java.lang.Exception
    */
    @Before

    public void setUp() throws Exception
    num1 =1;
    num2= 2;
    num4 = 4;
    num3 = 3;
    num5 = 5;
    game= new Game();


    @Test
    public void testchoosePlayers2()

    System.out.println("Testing choosingPlayers 2");
    Scanner scanner = new Scanner (System.in);
    int expected = scanner.nextInt();
    int actual = game.choosePlayers(num2);
    assertEquals(expected, actual);
    System.out.println("Test finsihed");



    @Test
    public void testchoosePlayers3()
    System.out.println("Testing choosingPlayers 3");
    Scanner scanner = new Scanner (System.in);
    int expected = scanner.nextInt();
    int actual = game.choosePlayers(num3);
    assertEquals(expected, actual);
    System.out.println("Test finsihed");




    @Test
    public void testchoosePlayers4()
    System.out.println("Testing choosingPlayers 4");
    Scanner scanner = new Scanner (System.in);
    int expected = scanner.nextInt();
    int actual = game.choosePlayers(num4);
    assertEquals(expected, actual);
    System.out.println("Test finsihed");




    Every time I try and run this test only the first test will run and the scanner is not re-prompted for the subsequent 2. Is there any way around this? I would greatly appreciate any advice concerning this issue or for a better/more efficient way to test the above method .










    share|improve this question
























      0












      0








      0








      I am currently trying to Junit test a game for a Uni assignment. Below is an example of the kind of methods I am trying to test.



      public static int choosePlayers(int num) 
      while (validPlayerNumber == false)
      try
      System.out.print("Please enter Number of players (2-4)n> ");
      num = in.nextInt();
      switch (num)
      case 2:
      validPlayerNumber = true;
      numberPlayers = num;
      System.out.println(numberPlayers + " players selected");
      break;
      case 3:
      validPlayerNumber = true;
      numberPlayers = num;
      System.out.println(numberPlayers + " players selected");
      break;
      case 4:
      validPlayerNumber = true;
      numberPlayers = num;
      System.out.println(numberPlayers + " players selected");
      break;
      default:
      throw new IllegalArgumentException("Sorry, that is not a valid selection.");
      // System.out.println("Sorry, that is not a valid selection.");

      catch (InputMismatchException ex)
      // log the exception
      System.out.println("Problem with input : " + ex.toString());
      continue;


      return numberPlayers;



      I am using the following test class to test this:



      /**
      * @throws java.lang.Exception
      */
      @Before

      public void setUp() throws Exception
      num1 =1;
      num2= 2;
      num4 = 4;
      num3 = 3;
      num5 = 5;
      game= new Game();


      @Test
      public void testchoosePlayers2()

      System.out.println("Testing choosingPlayers 2");
      Scanner scanner = new Scanner (System.in);
      int expected = scanner.nextInt();
      int actual = game.choosePlayers(num2);
      assertEquals(expected, actual);
      System.out.println("Test finsihed");



      @Test
      public void testchoosePlayers3()
      System.out.println("Testing choosingPlayers 3");
      Scanner scanner = new Scanner (System.in);
      int expected = scanner.nextInt();
      int actual = game.choosePlayers(num3);
      assertEquals(expected, actual);
      System.out.println("Test finsihed");




      @Test
      public void testchoosePlayers4()
      System.out.println("Testing choosingPlayers 4");
      Scanner scanner = new Scanner (System.in);
      int expected = scanner.nextInt();
      int actual = game.choosePlayers(num4);
      assertEquals(expected, actual);
      System.out.println("Test finsihed");




      Every time I try and run this test only the first test will run and the scanner is not re-prompted for the subsequent 2. Is there any way around this? I would greatly appreciate any advice concerning this issue or for a better/more efficient way to test the above method .










      share|improve this question














      I am currently trying to Junit test a game for a Uni assignment. Below is an example of the kind of methods I am trying to test.



      public static int choosePlayers(int num) 
      while (validPlayerNumber == false)
      try
      System.out.print("Please enter Number of players (2-4)n> ");
      num = in.nextInt();
      switch (num)
      case 2:
      validPlayerNumber = true;
      numberPlayers = num;
      System.out.println(numberPlayers + " players selected");
      break;
      case 3:
      validPlayerNumber = true;
      numberPlayers = num;
      System.out.println(numberPlayers + " players selected");
      break;
      case 4:
      validPlayerNumber = true;
      numberPlayers = num;
      System.out.println(numberPlayers + " players selected");
      break;
      default:
      throw new IllegalArgumentException("Sorry, that is not a valid selection.");
      // System.out.println("Sorry, that is not a valid selection.");

      catch (InputMismatchException ex)
      // log the exception
      System.out.println("Problem with input : " + ex.toString());
      continue;


      return numberPlayers;



      I am using the following test class to test this:



      /**
      * @throws java.lang.Exception
      */
      @Before

      public void setUp() throws Exception
      num1 =1;
      num2= 2;
      num4 = 4;
      num3 = 3;
      num5 = 5;
      game= new Game();


      @Test
      public void testchoosePlayers2()

      System.out.println("Testing choosingPlayers 2");
      Scanner scanner = new Scanner (System.in);
      int expected = scanner.nextInt();
      int actual = game.choosePlayers(num2);
      assertEquals(expected, actual);
      System.out.println("Test finsihed");



      @Test
      public void testchoosePlayers3()
      System.out.println("Testing choosingPlayers 3");
      Scanner scanner = new Scanner (System.in);
      int expected = scanner.nextInt();
      int actual = game.choosePlayers(num3);
      assertEquals(expected, actual);
      System.out.println("Test finsihed");




      @Test
      public void testchoosePlayers4()
      System.out.println("Testing choosingPlayers 4");
      Scanner scanner = new Scanner (System.in);
      int expected = scanner.nextInt();
      int actual = game.choosePlayers(num4);
      assertEquals(expected, actual);
      System.out.println("Test finsihed");




      Every time I try and run this test only the first test will run and the scanner is not re-prompted for the subsequent 2. Is there any way around this? I would greatly appreciate any advice concerning this issue or for a better/more efficient way to test the above method .







      java java.util.scanner junit4






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 8 at 17:38









      Emma Cox Emma Cox

      24




      24






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Your purpose here is to test that method returns correct values with provided input parameters. If you scan incorrect value test will fail. So instead of scanning expected value just put expected value to the assertion. Also you don't need separate tests here, since you test the same functionality.



          To simulate input you will need to replace System.in with your own input stream. See JUnit: How to simulate System.in testing? for details.




          private final InputStream systemIn = System.in;
          private ByteArrayInputStream testIn;

          @After
          public void resetSystemIn()
          System.setIn(systemIn);


          private void inputData(String data)
          testIn = new ByteArrayInputStream(data.getBytes());
          System.setIn(testIn);


          @Test
          public void testchoosePlayers()
          System.out.println("Testing choosingPlayers 2");
          inputData("2");
          int actual = game.choosePlayers(num2);
          assertEquals(num2, actual);
          System.out.println("Testing choosingPlayers 3");
          inputData("3");
          actual = game.choosePlayers(num3);
          assertEquals(num3, actual);
          System.out.println("Testing choosingPlayers 4");
          inputData("4");
          actual = game.choosePlayers(num4);
          assertEquals(num4, actual);
          System.out.println("Test finsihed");






          share|improve this answer

























          • Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

            – Emma Cox
            Mar 8 at 18:40











          • int num parameter confused me. See answer updated.

            – devmind
            Mar 8 at 19:21











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068303%2fjunit-test-scanner-input-issue%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Your purpose here is to test that method returns correct values with provided input parameters. If you scan incorrect value test will fail. So instead of scanning expected value just put expected value to the assertion. Also you don't need separate tests here, since you test the same functionality.



          To simulate input you will need to replace System.in with your own input stream. See JUnit: How to simulate System.in testing? for details.




          private final InputStream systemIn = System.in;
          private ByteArrayInputStream testIn;

          @After
          public void resetSystemIn()
          System.setIn(systemIn);


          private void inputData(String data)
          testIn = new ByteArrayInputStream(data.getBytes());
          System.setIn(testIn);


          @Test
          public void testchoosePlayers()
          System.out.println("Testing choosingPlayers 2");
          inputData("2");
          int actual = game.choosePlayers(num2);
          assertEquals(num2, actual);
          System.out.println("Testing choosingPlayers 3");
          inputData("3");
          actual = game.choosePlayers(num3);
          assertEquals(num3, actual);
          System.out.println("Testing choosingPlayers 4");
          inputData("4");
          actual = game.choosePlayers(num4);
          assertEquals(num4, actual);
          System.out.println("Test finsihed");






          share|improve this answer

























          • Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

            – Emma Cox
            Mar 8 at 18:40











          • int num parameter confused me. See answer updated.

            – devmind
            Mar 8 at 19:21















          1














          Your purpose here is to test that method returns correct values with provided input parameters. If you scan incorrect value test will fail. So instead of scanning expected value just put expected value to the assertion. Also you don't need separate tests here, since you test the same functionality.



          To simulate input you will need to replace System.in with your own input stream. See JUnit: How to simulate System.in testing? for details.




          private final InputStream systemIn = System.in;
          private ByteArrayInputStream testIn;

          @After
          public void resetSystemIn()
          System.setIn(systemIn);


          private void inputData(String data)
          testIn = new ByteArrayInputStream(data.getBytes());
          System.setIn(testIn);


          @Test
          public void testchoosePlayers()
          System.out.println("Testing choosingPlayers 2");
          inputData("2");
          int actual = game.choosePlayers(num2);
          assertEquals(num2, actual);
          System.out.println("Testing choosingPlayers 3");
          inputData("3");
          actual = game.choosePlayers(num3);
          assertEquals(num3, actual);
          System.out.println("Testing choosingPlayers 4");
          inputData("4");
          actual = game.choosePlayers(num4);
          assertEquals(num4, actual);
          System.out.println("Test finsihed");






          share|improve this answer

























          • Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

            – Emma Cox
            Mar 8 at 18:40











          • int num parameter confused me. See answer updated.

            – devmind
            Mar 8 at 19:21













          1












          1








          1







          Your purpose here is to test that method returns correct values with provided input parameters. If you scan incorrect value test will fail. So instead of scanning expected value just put expected value to the assertion. Also you don't need separate tests here, since you test the same functionality.



          To simulate input you will need to replace System.in with your own input stream. See JUnit: How to simulate System.in testing? for details.




          private final InputStream systemIn = System.in;
          private ByteArrayInputStream testIn;

          @After
          public void resetSystemIn()
          System.setIn(systemIn);


          private void inputData(String data)
          testIn = new ByteArrayInputStream(data.getBytes());
          System.setIn(testIn);


          @Test
          public void testchoosePlayers()
          System.out.println("Testing choosingPlayers 2");
          inputData("2");
          int actual = game.choosePlayers(num2);
          assertEquals(num2, actual);
          System.out.println("Testing choosingPlayers 3");
          inputData("3");
          actual = game.choosePlayers(num3);
          assertEquals(num3, actual);
          System.out.println("Testing choosingPlayers 4");
          inputData("4");
          actual = game.choosePlayers(num4);
          assertEquals(num4, actual);
          System.out.println("Test finsihed");






          share|improve this answer















          Your purpose here is to test that method returns correct values with provided input parameters. If you scan incorrect value test will fail. So instead of scanning expected value just put expected value to the assertion. Also you don't need separate tests here, since you test the same functionality.



          To simulate input you will need to replace System.in with your own input stream. See JUnit: How to simulate System.in testing? for details.




          private final InputStream systemIn = System.in;
          private ByteArrayInputStream testIn;

          @After
          public void resetSystemIn()
          System.setIn(systemIn);


          private void inputData(String data)
          testIn = new ByteArrayInputStream(data.getBytes());
          System.setIn(testIn);


          @Test
          public void testchoosePlayers()
          System.out.println("Testing choosingPlayers 2");
          inputData("2");
          int actual = game.choosePlayers(num2);
          assertEquals(num2, actual);
          System.out.println("Testing choosingPlayers 3");
          inputData("3");
          actual = game.choosePlayers(num3);
          assertEquals(num3, actual);
          System.out.println("Testing choosingPlayers 4");
          inputData("4");
          actual = game.choosePlayers(num4);
          assertEquals(num4, actual);
          System.out.println("Test finsihed");







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 19:19

























          answered Mar 8 at 18:29









          devminddevmind

          1449




          1449












          • Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

            – Emma Cox
            Mar 8 at 18:40











          • int num parameter confused me. See answer updated.

            – devmind
            Mar 8 at 19:21

















          • Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

            – Emma Cox
            Mar 8 at 18:40











          • int num parameter confused me. See answer updated.

            – devmind
            Mar 8 at 19:21
















          Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

          – Emma Cox
          Mar 8 at 18:40





          Thank you for your advice, unfortunately when I run the test, the scanner from the method being tested Is still called and asks for an number input, negating the values I set in the test data (num1 , num2 etc). Do you have any advice concerning this?

          – Emma Cox
          Mar 8 at 18:40













          int num parameter confused me. See answer updated.

          – devmind
          Mar 8 at 19:21





          int num parameter confused me. See answer updated.

          – devmind
          Mar 8 at 19:21



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068303%2fjunit-test-scanner-input-issue%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

          2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme