vendredi 1 novembre 2019

Got user input from a for loop in a JUnit test, now how to actually test its output?

So suppose I have the following class with methodA():

public class example {

public void methodA() {
    System.out.println("Enter in an integer for each step.\n");
    Scanner scan = new Scanner(System.in); 
    int currentStepCount = 0; 
    int totalStepCount = 0;

    for (int step = 10; step <= 16; step++) {
        if (step == 15)
            continue; // Skip fifteenth step

        System.out.println("\nStep " + step + ": ");
        currentStepCount = scan.nextInt();

        totalStepCount += currentStepCount;
    }

    System.out.println("\n\nAll steps have been taken in.\n");
    System.out.println("Total step count comes out to: " + totalStepCount + "\n"); 
    System.out.println("The last step count was " + currentStepCount + ". \n");
}
}

And I have a JUnit test that's able to simulate the input:

class junitTests {
private final ByteArrayOutputStream output = new ByteArrayOutputStream();

@Before
public void setUpStreams() {
    System.setOut(new PrintStream(output));
}
@Test
void testA() {
    example ex = new example();
    ByteArrayInputStream in1 = new ByteArrayInputStream("13\n13\n13\n13\n13\n13\n".getBytes());

    System.setIn(in1);
    ex.methodA();
    String out = output.toString(); 

    System.out.println(out);
}
}

but I'm stuck on how to actually test whether the output is the correct output. When I try to print ByteArrayOutputStream output it comes out as empty so when I try to do an assertEquals method, it always fails. How can actually make it so that output is not always empty. Or, more generally, how can I actually test the output of the method altogether. Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire