easy-random icon indicating copy to clipboard operation
easy-random copied to clipboard

How to use same radomized value for 2 member variable in a pojo

Open sylwa opened this issue 2 years ago • 1 comments

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

sylwa avatar Jun 29 '22 04:06 sylwa

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);
  }

dvgaba avatar Sep 23 '22 12:09 dvgaba

@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())

vadim-levotsky avatar Feb 02 '23 21:02 vadim-levotsky

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.

fmbenhassine avatar Oct 01 '23 21:10 fmbenhassine