简体   繁体   中英

How can I test next code with JUnit

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);
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM