|
| 1 | +package com.thealgorithms.others; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | + |
| 6 | +import java.io.ByteArrayOutputStream; |
| 7 | +import java.io.PrintStream; |
| 8 | +import org.junit.jupiter.api.AfterEach; |
| 9 | +import org.junit.jupiter.api.BeforeEach; |
| 10 | +import org.junit.jupiter.api.Test; |
| 11 | + |
| 12 | +public class TowerOfHanoiTest { |
| 13 | + |
| 14 | + private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream(); |
| 15 | + private final PrintStream standardOut = System.out; |
| 16 | + |
| 17 | + @BeforeEach |
| 18 | + public void setUp() { |
| 19 | + System.setOut(new PrintStream(outputStreamCaptor)); |
| 20 | + } |
| 21 | + |
| 22 | + @AfterEach |
| 23 | + public void tearDown() { |
| 24 | + System.setOut(standardOut); |
| 25 | + } |
| 26 | + |
| 27 | + @Test |
| 28 | + public void testShiftWithNullDiscs() { |
| 29 | + TowerOfHanoi.shift(1, null, null, null); |
| 30 | + String expectedOutput = "Move 1 from null to null\n"; |
| 31 | + assertEquals(expectedOutput, outputStreamCaptor.toString()); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + public void testShiftWithNegativeMove() { |
| 36 | + assertThrows(StackOverflowError.class, () -> { TowerOfHanoi.shift(-1, "A", "B", "C"); }); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + public void testShiftWithThreeDiscs() { |
| 41 | + TowerOfHanoi.shift(3, "A", "B", "C"); |
| 42 | + String expectedOutput = "Move 1 from A to C\n" |
| 43 | + + "Move 2 from A to B\n" |
| 44 | + + "Move 1 from C to B\n" |
| 45 | + + "Move 3 from A to C\n" |
| 46 | + + "Move 1 from B to A\n" |
| 47 | + + "Move 2 from B to C\n" |
| 48 | + + "Move 1 from A to C\n"; |
| 49 | + assertEquals(expectedOutput, outputStreamCaptor.toString()); |
| 50 | + } |
| 51 | +} |
0 commit comments