diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java new file mode 100644 index 0000000000..05b398371c --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/Direction.java @@ -0,0 +1,22 @@ +package com.baeldung.enums.randomenum; + +import java.util.Random; + +/** + * Represents directions. + */ +public enum Direction { + EAST, WEST, SOUTH, NORTH; + + private static final Random PRNG = new Random(); + + /** + * Generate a random direction. + * + * @return a random direction + */ + public static Direction randomDirection() { + Direction[] directions = values(); + return directions[PRNG.nextInt(directions.length)]; + } +} diff --git a/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java new file mode 100644 index 0000000000..33d793062d --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/main/java/com/baeldung/enums/randomenum/RandomEnumGenerator.java @@ -0,0 +1,17 @@ +package com.baeldung.enums.randomenum; + +import java.util.Random; + +public class RandomEnumGenerator> { + + private static final Random PRNG = new Random(); + private final T[] values; + + public RandomEnumGenerator(Class e) { + values = e.getEnumConstants(); + } + + public T randomEnum() { + return values[PRNG.nextInt(values.length)]; + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java new file mode 100644 index 0000000000..76b4bf1e74 --- /dev/null +++ b/core-java-modules/core-java-lang-oop-types-2/src/test/java/com/baeldung/enums/randomenum/RandomEnumUnitTest.java @@ -0,0 +1,23 @@ +package com.baeldung.enums.randomenum; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RandomEnumUnitTest { + + @Test + public void givenEnumType_whenUsingStaticMethod_valueIsRandomlyGenerated() { + Direction direction = Direction.randomDirection(); + assertThat(direction).isNotNull(); + assertThat(direction instanceof Direction); + } + + @Test + public void givenEnumType_whenGeneratingRandomValue_valueIsOfClassAndNotNull() { + RandomEnumGenerator reg = new RandomEnumGenerator(Direction.class); + Object direction = reg.randomEnum(); + assertThat(direction).isNotNull(); + assertThat(direction instanceof Direction); + } +}