Public feed
#894172
package gameoflife2;import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.lang.reflect.Field;import java.lang.reflect.Modifier;import junit.framework.TestCase;public class GameOfLifeTest extends TestCase { private void testWillLive(boolean isLive, int neighbourCount, boolean expected) { assertEquals(expected, GameOfLife.willLive(isLive, neighbourCount)); } public void testWillLive() { testWillLive(false, 0, false); testWillLive(false, 1, false); testWillLive(false, 2, false); testWillLive(false, 3, true); testWillLive(false, 4, false); testWillLive(false, 5, false); testWillLive(false, 6, false); testWillLive(false, 7, false); testWillLive(false, 8, false); testWillLive(true, 0, false); testWillLive(true, 1, false); testWillLive(true, 2, true); testWillLive(true, 3, true); testWillLive(true, 4, false); testWillLive(true, 5, false); testWillLive(true, 6, false); testWillLive(true, 7, false); testWillLive(true, 8, false); } static void setColony(Colony colony, int y, int x, int w, int h, int values) { for (int dy = 0; dy < h; dy++) { for (int dx = 0; dx < w; dx++) { colony.setCell(y + dy, x + dx, (values & 1) == 1); values >>= 1; } } } public void testStepColony() { Colony colony = new Colony(3, 3), nextColony = new Colony(3, 3); for (int i = 0; i < (1 << 9); i++) { setColony(colony, 1, 1, 3, 3, i); setColony(nextColony, 1, 1, 3, 3, i); int changes = GameOfLife.stepColony(colony, nextColony); for (int y = 0; y < colony.getHeight(); y++) { for (int x = 0; x < colony.getWidth(); x++) { boolean current = colony.getCell(y, x); boolean next = nextColony.getCell(y, x); assertEquals(GameOfLife.willLive(current, colony.countNeighbours(y, x)), next); if (next != current) { changes--; } } } assertEquals(0, changes); } } private void testMain(String colony, int expected) { PrintStream oldOut = System.out; ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); try { GameOfLife.main(colony.split("\n")); } catch (RuntimeException e) { e.printStackTrace(); } String result = out.toString(); out.reset(); boolean matches = result.matches("(?s).*" + String.valueOf(expected) + "\\s*"); assertTrue(matches); System.setOut(oldOut); } public final static String glider004 = "**\n" + "* *\n" + "*\n"; public final static String flipFlop100 = " *.\n" + " *.\n" + ".* \n"; public void testMain() { Field[] fields = GameOfLifeTest.class.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (field.getType() != String.class) { continue; } if (field.getModifiers() != (Modifier.PUBLIC | Modifier.FINAL | Modifier.STATIC)) { continue; } String name = field.getName(); try { testMain((String)field.get(null), Integer.valueOf(name.substring(name.length() - 3))); } catch (Exception e) { } } }}