Skip to content

Instantly share code, notes, and snippets.

@alessiogambi
Created November 30, 2020 12:54
Show Gist options
  • Save alessiogambi/75d9287173d064db2bf2ec67f1337ae2 to your computer and use it in GitHub Desktop.
Save alessiogambi/75d9287173d064db2bf2ec67f1337ae2 to your computer and use it in GitHub Desktop.
Create Unit tests for Testing Minesweeper in Eclipse/Java
/**
* The following test must be store in the root package of your Java project. The test is taked from the
* Programming Styles WiSe 20-21 Basic Test Case. To make it work you need the following dependencies in your project:
- JUnit 4.12
- Hamcrest 2.2
- Apache Commons Lang3 3.10
- JUnit System Rules 1.19 (https://stefanbirkner.github.io/system-rules/download.html)
*
* @author gambi
*/
import java.io.File;
import java.io.PrintWriter;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
import org.junit.rules.TemporaryFolder;
public class GistTests {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
// Make sure that JVM does not exit when MineSweeper calls System.exit
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Rule
public final TextFromStandardInputStream systemInMock = TextFromStandardInputStream.emptyStandardInputStream();
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Test
public void testThatGivenCorrectInputsTheProgramExitNormally() throws Exception {
// Create a temporary file.
final File boardCfgFile = tempFolder.newFile("simple.cfg");
// Write the simple 3x3 board to the file
try (PrintWriter out = new PrintWriter(boardCfgFile)) {
out.println("..*");
out.println("...");
out.println("...");
}
// Provide the following lines on stdin
systemInMock.provideLines(" 1 1 R");
// Define the expectation upon Exit Code
// NOTE: This requires that main calls System.exit(0); otherwise the test fails !
exit.expectSystemExitWithStatus(0);
// Run the main method
Minesweeper.main(new String[] { boardCfgFile.getAbsolutePath() });
// here you can find the output produced by "Minesweeper" stored in a String
String stdOut = systemOutRule.getLog();
System.out.println(" STD OUT IS \n" + stdOut);
}
@Test
public void testNonRectangularConfiguration() throws Exception {
// Create a file that has invalid content (lines have different lenght!)
final File boardCfgFile = tempFolder.newFile("simple.cfg");
try (PrintWriter out = new PrintWriter(boardCfgFile)) {
out.println("...");
out.println("*");
}
// We expect that the system exits with exit code 2
exit.expectSystemExitWithStatus(2);
Minesweeper.main(new String[] { boardCfgFile.getAbsolutePath() });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment