Random random = new Random(); random.setSeed(1234L); System.out.println(random.nextInt(100)); // prints 55 random.setSeed(1234L); System.out.println(random.nextInt(100)); // prints 55 again
@Test public void testMyFunctionWithRandomInput() { Random random = new Random(); long seed = System.currentTimeMillis(); random.setSeed(seed); int input = random.nextInt(100); int expectedOutput = ... // calculate expected output based on input int actualOutput = myFunction(input); assertEquals(expectedOutput, actualOutput); // repeat with same input and seed random.setSeed(seed); actualOutput = myFunction(input); assertEquals(expectedOutput, actualOutput); }In this example, we demonstrate how to use setSeed() to test a function that takes random input. We create a new Random instance and set its seed based on the current time (to get a unique seed for each invocation). Then, we generate a random integer between 0 and 99 and use it as input for our function. We calculate the expected output based on the input and compare it to the actual output. Finally, we repeat the test with the same input and seed to ensure that the function produces the same output each time. Overall, setSeed() is a useful method for controlling the randomness of your application and ensuring deterministic behavior in certain scenarios.