Skip to content

Add tests Tower of Hanoi #5736

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 25, 2024
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions src/test/java/com/thealgorithms/others/TowerOfHanoiTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.thealgorithms.others;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class TowerOfHanoiTest {

private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();
private final PrintStream standardOut = System.out;

@BeforeEach
public void setUp() {
System.setOut(new PrintStream(outputStreamCaptor));
}

@AfterEach
public void tearDown() {
System.setOut(standardOut);
}

@Test
public void testShiftWithNullDiscs() {
TowerOfHanoi.shift(1, null, null, null);
String expectedOutput = "Move 1 from null to null\n";
assertEquals(expectedOutput, outputStreamCaptor.toString());
}

@Test
public void testShiftWithNegativeMove() {
assertThrows(StackOverflowError.class, () -> { TowerOfHanoi.shift(-1, "A", "B", "C"); });
}

@Test
public void testShiftWithThreeDiscs() {
TowerOfHanoi.shift(3, "A", "B", "C");
String expectedOutput = "Move 1 from A to C\n"
+ "Move 2 from A to B\n"
+ "Move 1 from C to B\n"
+ "Move 3 from A to C\n"
+ "Move 1 from B to A\n"
+ "Move 2 from B to C\n"
+ "Move 1 from A to C\n";
assertEquals(expectedOutput, outputStreamCaptor.toString());
}
}