easy-random
easy-random copied to clipboard
How to use same radomized value for 2 member variable in a pojo
I am trying to generate pojo with random values. My expectation is 2 member variables to have the same generated randomized value.
.randomize(named("codeType|codeDescription").and(ofType(String.class)).and(inClass(Country.class)), () -> genericStringRandomizer.getRandomValue())
Expecting both codeType and codeDescription to have the same value. But unable to achieve it. Can you please advise on how to achieve this.
Thanks
Seed and call order needs to be same for this to work. Something like below should work
@Test
void generateSame() {
long testSeed = new Random().nextInt(1000);
EasyRandomParameters parameters = new EasyRandomParameters().randomize(
FieldPredicates.named("code"), () -> new StringRandomizer(testSeed).getRandomValue()).randomize(
FieldPredicates.named("codeDesc"), () -> new StringRandomizer(testSeed).getRandomValue());
EasyRandom easyRandom = new EasyRandom(parameters);
CodeInfo bean = easyRandom.nextObject(CodeInfo.class);
Assertions.assertThat(bean).isNotNull();
Assertions.assertThat(bean.code).isEqualTo(bean.codeDesc);
}
@sylwa Have you tried this approach?
EasyRandomParameters parameters = new EasyRandomParameters().randomize(
FieldPredicates.named("codeType").or(FieldPredicates.named("codeDescription"))
.and(FieldPredicates.ofType(String.class))
.and(FieldPredicates.inClass(Country.class)),
() -> genericStringRandomizer.getRandomValue())
Using the same randomizer for two fields won't work as there will be two different calls to the underlying Random
instance that was initialized with the same seed. As mentioned by @dvgaba , you need to have the same seed and the same call order to achieve that. Otherwise you can use a custom context aware randomizer that generates a random value and then set it on the required target fields.