Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala or Java equivalent of Ruby factory_girl or Python factory_boy (convenient factory pattern for unit testing)

When I am writing unit tests in dynamically-typed Ruby or Python, I use the libraries factory_girl and factory_boy, respectively, in order to conveniently generate objects under test. They provide convenient features over direct object instantiation, for example:

  • factory inheritance and overrides
  • field defaults and overrides
  • lazily-computed dependent/derived fields
  • construction of dependent/related other objects
  • implicit lazy field dependency resolution

What are some libraries/frameworks I could use while writing unit tests in statically-typed Java or Scala to achieve similar effects with similar benefits?

Thanks in advance!

I found a similar StackOverflow question from the past here, but unfortunately, the top answer is (paraphrased), "there is no direct equivalent because that would be pointless".

like image 818
Ming Avatar asked Feb 18 '15 04:02

Ming


2 Answers

There is a project called Fixture-Factory(https://github.com/six2six/fixture-factory). It was based in the Factory-Girl's idea.

You could easily create your object's template definition:

Fixture.of(Client.class).addTemplate("valid", new Rule(){{
  add("id", random(Long.class, range(1L, 200L)));
  add("name", random("Anderson Parra", "Arthur Hirata"));
  add("nickname", random("nerd", "geek"));
  add("email", "${nickname}@gmail.com");
  add("birthday", instant("18 years ago"));
  add("address", one(Address.class, "valid"));
}});

And then you can easily use it in your tests:
Client client = Fixture.from(Client.class).gimme("valid");

like image 173
Nykolas Lima Avatar answered Oct 27 '22 17:10

Nykolas Lima


I created a new java framework Factory Duke to provide the same feature as Factory_Girl https://github.com/regis-leray/factory_duke

Really easy to use, define a template (in this case the default)

FactoryDuke.define(User.class, u -> {
    u.setLastName("Scott");
    u.setName("Malcom");
    u.setRole(model.Role.USER);
});

And use it

User user = FactoryDuke.build(User.class);

Please read the document to see advanced features

like image 44
Regis dev Avatar answered Oct 27 '22 17:10

Regis dev