Skip to content

Commit 2d9fea5

Browse files
Merge pull request eugenp#12107 from chrisjaimes/random_enum_value
added randomDirection method to Enum. Created RandomEnumGenerator
2 parents ea44315 + 2543fb5 commit 2d9fea5

3 files changed

Lines changed: 62 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.enums.randomenum;
2+
3+
import java.util.Random;
4+
5+
/**
6+
* Represents directions.
7+
*/
8+
public enum Direction {
9+
EAST, WEST, SOUTH, NORTH;
10+
11+
private static final Random PRNG = new Random();
12+
13+
/**
14+
* Generate a random direction.
15+
*
16+
* @return a random direction
17+
*/
18+
public static Direction randomDirection() {
19+
Direction[] directions = values();
20+
return directions[PRNG.nextInt(directions.length)];
21+
}
22+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.baeldung.enums.randomenum;
2+
3+
import java.util.Random;
4+
5+
public class RandomEnumGenerator<T extends Enum<T>> {
6+
7+
private static final Random PRNG = new Random();
8+
private final T[] values;
9+
10+
public RandomEnumGenerator(Class<T> e) {
11+
values = e.getEnumConstants();
12+
}
13+
14+
public T randomEnum() {
15+
return values[PRNG.nextInt(values.length)];
16+
}
17+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.enums.randomenum;
2+
3+
import org.junit.Test;
4+
5+
import static org.assertj.core.api.Assertions.assertThat;
6+
7+
public class RandomEnumUnitTest {
8+
9+
@Test
10+
public void givenEnumType_whenUsingStaticMethod_valueIsRandomlyGenerated() {
11+
Direction direction = Direction.randomDirection();
12+
assertThat(direction).isNotNull();
13+
assertThat(direction instanceof Direction);
14+
}
15+
16+
@Test
17+
public void givenEnumType_whenGeneratingRandomValue_valueIsOfClassAndNotNull() {
18+
RandomEnumGenerator reg = new RandomEnumGenerator(Direction.class);
19+
Object direction = reg.randomEnum();
20+
assertThat(direction).isNotNull();
21+
assertThat(direction instanceof Direction);
22+
}
23+
}

0 commit comments

Comments
 (0)