MrWalterWhite
MrWalterWhite

Reputation: 45

Instancio - Generate past date as string format YYYYMMDD

I'm trying to use Instancio to generate data for testing. The Student class has a birthdate member as a String type to store the date in the format YYYYMMDD.

How can I use Instancio library (test data generator) to generate a date in the format yyyyMMdd as string?

Here was my starting point:

Student student = Instancio.of(Student.class)
  .generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past())
  .create();

Thx

Upvotes: 1

Views: 1096

Answers (1)

armandino
armandino

Reputation: 18562

As suggested in the comments, it's a good practice to declare the field as a LocalDate instead of a String. If you cannot change that, you can map the date to a string using the as() method:

Student student = Instancio.of(Student.class)
  .generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past().as(dob -> dob.format(DateTimeFormatter.BASIC_ISO_DATE)))
  .create();

Upvotes: 1

Related Questions