import java.util.Random; import lab.Color; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * Test case for the lab.Color class. * * @author Franck van Breugel */ public class ColorTest { /** * Tests the constructor and accessors for each RGB combination. */ @Test public void testConstructorAndAccessors() { for (int r = Byte.MIN_VALUE; r <= Byte.MAX_VALUE; r++) { for (int g = Byte.MIN_VALUE; g <= Byte.MAX_VALUE; g++) { for (int b = Byte.MIN_VALUE; b <= Byte.MAX_VALUE; b++) { Color color = new Color((byte) r, (byte) g, (byte) b); Assertions.assertNotNull(color, "Constructed object is null"); Assertions.assertEquals(r, color.getRed(), "Accessor of red returns the incorrect value"); Assertions.assertEquals(g, color.getGreen(), "Accessor of green returns the incorrect value"); Assertions.assertEquals(b, color.getBlue(), "Accessor of blue returns the incorrect value"); } } } } /** * Tests that the constant BLACK is not null. */ @Test public void testBLACK() { Assertions.assertNotNull(Color.BLACK, "The constant BLACK is null"); } /** * Tests the equals method. */ @Test public void testEquals() { for (int r = Byte.MIN_VALUE; r <= Byte.MAX_VALUE; r++) { for (int g = Byte.MIN_VALUE; g <= Byte.MAX_VALUE; g++) { for (int b = Byte.MIN_VALUE; b <= Byte.MAX_VALUE; b++) { Color color = new Color((byte) r, (byte) g, (byte) b); Object object = new Object(); Color copy = new Color((byte) r, (byte) g, (byte) b); Assertions.assertFalse(color.equals(null), "null is equal to a Color"); Assertions.assertFalse(color.equals(object), "An Object is equal to a Color"); Assertions.assertTrue(color.equals(color), "A Color is not equal to itself"); Assertions.assertTrue(color.equals(copy), "A Color is not equal to another color with the same RGB values"); } } } } /** * Tests the equals method for different Color objects. */ @Test public void testEqualsRandomly() { final int CASES = 100000000; Random random = new Random(); for (int c = 0; c < CASES; c++) { byte b = (byte) (Byte.MIN_VALUE + random.nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE)); byte r = (byte) (Byte.MIN_VALUE + random.nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE)); byte g = (byte) (Byte.MIN_VALUE + random.nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE)); Color one = new Color(r, g, b); b = (byte) (Byte.MIN_VALUE + random.nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE)); r = (byte) (Byte.MIN_VALUE + random.nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE)); g = (byte) (Byte.MIN_VALUE + random.nextInt(Byte.MAX_VALUE - Byte.MIN_VALUE)); Color other = new Color(r, g, b); Assertions.assertEquals(one.equals(other), one.getRed() == other.getRed() && one.getGreen() == other.getGreen() && one.getBlue() == other.getBlue(), "Comparison of two Colors failed"); } } }