另一个与 factory-bot(factory-girl 的新名称)非常相似的解决方案是
topicusoverheid/java-factory-bot您可以这样使用:
给定文章和用户的模型(省略了获取器和设置器):
@Data
public class Article {
private String title;
private String content;
private Date creationDate;
private User author;
}
@Data
public class User {
private String username;
private String firstName;
private String lastName;
private String email;
}
您可以定义工厂,例如
class ArticleFactory extends Factory<Article> {
Map<String, Attribute> attributes = [
title : value { faker.lorem().sentence() },
content : value { faker.lorem().paragraph() },
creationDate: value { faker.date().past(20, TimeUnit.DAYS) },
author : hasOne(UserFactory)
]
}
class UserFactory extends Factory<User> {
Map<String, Attribute> attributes = [
username : value { faker.name().username() },
firstName: value { faker.name().firstName() },
lastName : value { faker.name().lastName() },
email : value { "${get("firstName")}.${get("lastName")}@example.com" }
]
}
并使用创建对象
Article article = new ArticleFactory().build()
which generates an article with default random but sane attributes. Individual attributes or relations can be overriden by passing them in a map:
Article article = new ArticleFactory().build([title: "Foo", user: [username: "johndoe"]])