Alex Rivera | Logout

Does a framework like Factory Girl exist for Java?

Asked 2009-06-12T12:58:22.377
28

Factory Girl is a handy framework in rails for easily creating instances of models for testing.

From the Factory Girl home page:

factory_girl allows you to quickly define prototypes for each of your models and ask for instances with properties that are important to the test at hand.

An example (also from the home page):

Factory.sequence :email do |n|
    "somebody#{n}@example.com"
end

# Let's define a factory for the User model. The class name is guessed from the
# factory name.
Factory.define :user do |f|
    # These properties are set statically, and are evaluated when the factory is
    # defined.
    f.first_name 'John'
    f.last_name  'Doe'
    f.admin      false
    # This property is set "lazily." The block will be called whenever an
    # instance is generated, and the return value of the block is used as the
    # value for the attribute.
    f.email      { Factory.next(:email) }
end

if I need a user a can just call

test_user = Factory(:user, :admin => true)

which will yield a user with all the properties specified in the factory prototype, except for the admin property which I have specified explicitly. Also note that the email factory method will yield a different email each time it is called.

I'm thinking it should be pretty easy to implement something similar for Java, but I don't want to reinvent the wheel.

P.S: I know about both JMock and EasyMoc, however I am not talking about a mocking framework here.

Edit
Report

1 Answer

-3

If your model objects are simple, there is not reason to use a framework to create them, just simply use 'new' operator. If you have complex model (complex relationships) then you can use spring to bind them together (even in test scenarios you can use spring)

  • but this is simply for data objects, if you are talking about instantiating objects that are doing something, its recommended to mock/stub the external relationships instead of using real instances.
answered 2009-06-12T13:09:06.033

Your Answer