Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Dealing with Randomness - Part II

we can set the seed of the random number generator so that each time the test case runs it's predictable instead of pseudo-random; here's an example:

import org.testng.annotations.Test;
import java.util.Random;
import static org.testng.Assert.*;
class CoinFlipper {
public enum Face {HEAD, TAIL}
private Random random = new Random();
public Face flip() {
return random.nextBoolean() ? Face.HEAD : Face.TAIL;
void setRandom(final Random random) {
this.random = random;
public class CoinFlipperTest {
public void testFlip() {
final CoinFlipper flipper = new CoinFlipper();
final Random random = new Random(42);
assertEquals(flipper.flip(), CoinFlipper.Face.HEAD);
assertEquals(flipper.flip(), CoinFlipper.Face.TAIL);
assertEquals(flipper.flip(), CoinFlipper.Face.HEAD);
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content