added randomDirection method to Enum. Created RandomEnumGenerator. Added corresponding Unit Tests

This commit is contained in:
Christian Jaimes 2022-04-21 09:29:37 -04:00
parent b67525c5c1
commit 7093bdc456
3 changed files with 58 additions and 0 deletions

View File

@ -1,11 +1,25 @@
package com.baeldung.enums;
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)];
}
/**
* Finds direction by name.
*

View File

@ -0,0 +1,17 @@
package com.baeldung.enums;
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,27 @@
package com.baeldung.enums;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
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);
}
}