Skip to content

Commit 670b640

Browse files
saikatbhadrafmbenhassine
authored andcommitted
Change getUniqueJobParameters() to use random number generator that has a lower chance of repeating
Issue #821
1 parent 28768dc commit 670b640

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

spring-batch-test/src/main/java/org/springframework/batch/test/JobLauncherTestUtils.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
package org.springframework.batch.test;
1818

19+
import java.security.SecureRandom;
1920
import java.util.HashMap;
2021
import java.util.Map;
2122

@@ -160,7 +161,7 @@ public JobExecution launchJob(JobParameters jobParameters) throws Exception {
160161
*/
161162
public JobParameters getUniqueJobParameters() {
162163
Map<String, JobParameter> parameters = new HashMap<>();
163-
parameters.put("random", new JobParameter((long) (Math.random() * JOB_PARAMETER_MAXIMUM)));
164+
parameters.put("random", new JobParameter(new SecureRandom().nextLong()));
164165
return new JobParameters(parameters);
165166
}
166167

spring-batch-test/src/test/java/org/springframework/batch/test/JobLauncherTestUtilsTests.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import org.springframework.batch.core.ExitStatus;
2121
import org.springframework.batch.core.Job;
2222
import org.springframework.batch.core.JobExecution;
23+
import org.springframework.batch.core.JobParameters;
2324
import org.springframework.batch.core.Step;
2425
import org.springframework.batch.core.StepContribution;
2526
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
@@ -35,7 +36,11 @@
3536
import org.springframework.context.annotation.Configuration;
3637
import org.springframework.lang.Nullable;
3738

39+
import java.util.HashSet;
40+
import java.util.Set;
41+
3842
import static org.junit.Assert.assertEquals;
43+
import static org.junit.Assert.assertFalse;
3944

4045
/**
4146
* @author mminella
@@ -53,6 +58,18 @@ public void testStepExecutionWithJavaConfig() {
5358
assertEquals(ExitStatus.COMPLETED, execution.getExitStatus());
5459
}
5560

61+
@Test
62+
public void getUniqueJobParameters_doesNotRepeatJobParameters() {
63+
ApplicationContext context = new AnnotationConfigApplicationContext(TestJobConfiguration.class);
64+
JobLauncherTestUtils testUtils = context.getBean(JobLauncherTestUtils.class);
65+
Set<JobParameters> jobParametersSeen = new HashSet<>();
66+
for (int i = 0; i < 10_000; i++) {
67+
JobParameters jobParameters = testUtils.getUniqueJobParameters();
68+
assertFalse(jobParametersSeen.contains(jobParameters));
69+
jobParametersSeen.add(jobParameters);
70+
}
71+
}
72+
5673
@Configuration
5774
@EnableBatchProcessing
5875
public static class TestJobConfiguration {

0 commit comments

Comments
 (0)