英文:
Instancio - Generate past date as string format YYYYMMDD
问题
我试图使用Instancio来生成测试数据。Student类有一个名为birthdate的成员,类型为String,用于以YYYYMMDD的格式存储日期。
我该如何使用Instancio库(测试数据生成器)生成一个格式为yyyyMMdd的日期作为字符串?
这是我的起点:
Student student = Instancio.of(Student.class)
.generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past())
.create();
谢谢
英文:
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 poing:
Student student = Instancio.of(Student.class)
.generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past())
.create();
Thx
答案1
得分: 1
如评论中建议的,最好将字段声明为LocalDate
而不是String
。如果您不能更改它,可以使用as()
方法将日期映射到字符串:
Student student = Instancio.of(Student.class)
.generate(field(Student::getBirthdate), gen -> gen.temporal().localDate().past().as(dob -> dob.format(DateTimeFormatter.BASIC_ISO_DATE)))
.create();
英文:
As suggested in the comments, it's a good practice to declare the field as aLocalDate
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论