I have a simple function countUpDown(0, 3)
that needs to print some results like this: 0,1,2,3,2,1,0
class CountNumP2{
public void countUpDown(int start, int end) {
System.out.println(start);
if (start >= end) {
return;
}
countUpDown(start + 1, end);
System.out.println(start);
}
}
My function should work fine. However, when I did a JUnit test it fails like this:
import static org.junit.Assert.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Before;
import org.junit.Test;
public class CountNumP2Test {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@Test
public void test() {
CountNumP2 cn = new CountNumP2();
cn.countUpDown(0, 1);
String output = 0 + "\n" + 1 + "\n" + 0;
assertEquals(output , outContent.toString());
}
}
I think my test should pass, does anyone know the problem? Thank you so much
The expected output string that you are trying to assert should be
0\n1\n0\n
as there is a println.
Corrected unit test method should be as below.
@Test
public void test() {
CountNumP2 cn = new CountNumP2();
cn.countUpDown(0, 1);
String output = "0\n1\n0\n";
Assert.assertEquals(output , outContent.toString());
}