Merge pull request #12107 from chrisjaimes/random_enum_value

added randomDirection method to Enum. Created RandomEnumGenerator
This commit is contained in:
davidmartinezbarua 2022-04-28 11:30:10 -03:00 committed by GitHub
commit 01e30fef42
3 changed files with 62 additions and 0 deletions

View File

@ -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)];
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.enums.randomenum;
import java.util.Random;
public class RandomEnumGenerator<T extends Enum<T>> {
private static final Random PRNG = new Random();
private final T[] values;
public RandomEnumGenerator(Class<T> e) {
values = e.getEnumConstants();
}
public T randomEnum() {
return values[PRNG.nextInt(values.length)];
}
}

View File

@ -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);
}
}