0

I have the next code in java, I just used JUnit to test easy things and some execeptions, but how can I test the next function:

public static void suma() {
    Scanner scanner = new Scanner(System.in);
    int primerSumando = scanner.nextInt();
    int segundoSumando = scanner.nextInt();
    System.out.print(primerSumando+segundoSumando);
}
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Asier Gomez
  • 6,034
  • 18
  • 52
  • 105
  • 1
    Possible duplicate of [JUnit test for System.out.println()](http://stackoverflow.com/questions/1119385/junit-test-for-system-out-println) – Jordi Castilla Mar 07 '16 at 20:55

2 Answers2

0

You can achieve this by replacing default out print stream:

private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

private static PrintStream outBackup;

@BeforeClass
public static void backupOut() {
    outBackup = System.out;
}

@Before
public void setUpStreams() {
    System.setOut(new PrintStream(outContent));
}

@AfterClass
public static void cleanUpStreams() {
    System.setOut(outBackup);
}

@Test
public void out() {
    suma();
    assertEquals("4", outContent.toString());
}

But keep in mind that you must avoid using System.out directly. Use a logger or create a interface that receives operation result.

andrucz
  • 1,971
  • 2
  • 18
  • 30
-1

The hardcoded I/O will make it impossible to test with JUnit. A testable version would be to have suma() take an input stream and an output stream as parameters. In the real program, you pass in System.in and System.out. In JUnit, you can pass in String or StringBuffer streams, allowing your testcase to control the input and check the output.