java-faker icon indicating copy to clipboard operation
java-faker copied to clipboard

Idea: faker.randomlyNull(x)

Open wcarmon opened this issue 4 years ago • 6 comments
trafficstars

Is your feature request related to a problem? Please describe. for nullable fields, it's inconvenient to get a randomly null value.

  • Java: ThreadLocalRandom.current().nextBoolean() ? null : foo
  • Kotlin: if(ThreadLocalRandom.current().nextBoolean()) foo else foo

Describe the solution you'd like

// in faker.options() or similar
public <T> T randomlyNull(T foo) {
  return faker.options().option(null, foo);
}

Describe alternatives you've considered faker.options().option(null, foo);

Additional context Add any other context or screenshots about the feature request here.

wcarmon avatar Oct 08 '21 23:10 wcarmon

Hello, I just wanted to ask for a bit more clarification about the feature to be added. I have looked at the options file and see the different overridden functions. Do you want it so that the solution you described is added in as an override function? Any general information would also be helpful. Thank you.

akashrpatel621 avatar Oct 28 '21 20:10 akashrpatel621

Hello, if akashrpatel621 has decided to not work on the feature, then I volunteer to work on it in November/December. For the project maintainer, please let me know if this is okay and if you want it added.

LC24 avatar Nov 21 '21 13:11 LC24

Hello, I am still making progress trying to complete the issue but just wanted some clarification.

akashrpatel621 avatar Nov 21 '21 15:11 akashrpatel621

Just a regular function.

People can combine it with other functions like

var randomlyNullCity = faker.randomlyNull( faker.cities.name() );

wcarmon avatar Nov 21 '21 17:11 wcarmon

I have made a pr but just wanted more clarity so by combining functions are we trying to prevent null from being returned. Right now in my implementation that I derived from the initial issue. I return randomly null with the randomlyNull function.

akashrpatel621 avatar Dec 10 '21 00:12 akashrpatel621

@wcarmon

may be a bit too late but anyway there is a port of java-faker to jdk8 with lots of improvements including generation of collections with null rate https://github.com/datafaker-net/datafaker

for your case it could be done like that

new FakeCollection.Builder<Boolean>()
            .suppliers(() -> faker.bool().bool())
            .nullRate(0.5)
            .build()
            .singleton();

it will generate Boolean and with probability 0.5 it will return null

As you can see it is possible to use any provider here, so it could be applied not only for boolean

snuyanzin avatar Apr 22 '22 08:04 snuyanzin