像Factory Factory这样的框架是否存在? [英] Does a framework like Factory Girl exist for Java?

查看:159
本文介绍了像Factory Factory这样的框架是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


Factory Girl是一个方便的rails框架,可以轻松创建测试模型实例。

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

来自 Factory Girl主页


factory_girl允许您可以快速为每个模型定义原型,并要求具有对手头测试很重要的属性的实例。

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.

示例(也来自主页):

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)

这将产生具有工厂原型中指定的所有属性的用户 除了我明确指定的admin属性。另请注意,电子邮件工厂方法每次调用时都会生成不同的电子邮件。

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.

我认为实现类似Java的东西应该很容易,但是我不想重新发明轮子。

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

PS:我知道JMock和EasyMoc,但我不是在谈论一个模拟框架。

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

推荐答案

这样做的一个可能的库是篡夺者

One possible library for doing this is Usurper.

但是,如果要指定要创建的对象的属性,那么Java的静态类型会使框架毫无意义。您必须将属性名称指定为字符串,以便框架可以使用反射或Java Bean内省查找属性访问器。这将使重构变得更加困难。

However, if you want to specify properties of the objects you are creating, then Java's static typing makes a framework pointless. You'd have to specify the property names as strings so that the framework could look up property accessors using reflection or Java Bean introspection. That would make refactoring much more difficult.

只需更新对象并调用其方法就更简单了。如果您想在测试中避免大量的样板代码,测试数据生成器模式可以提供帮助。

It's much simpler to just new up the objects and call their methods. If you want to avoid lots of boilerplate code in tests, the Test Data Builder pattern can help.

这篇关于像Factory Factory这样的框架是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆