Factory Girl 是 Rails 中一个方便的框架,用于轻松创建模型实例以进行测试。
来自工厂女孩主页:
factory_girl 允许您为每个模型快速定义原型,并请求具有对手头测试很重要的属性的实例。
一个例子(也来自主页):
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
如果我需要一个用户可以打电话
test_user = Factory(:user, :admin => true)
这将产生一个具有工厂原型中指定的所有属性的用户,除了我明确指定的管理属性。另请注意,电子邮件工厂方法每次调用都会产生不同的电子邮件。
我认为为 Java 实现类似的东西应该很容易,但我不想重新发明轮子。
PS:我知道 JMock 和 EasyMoc,但是我不是在这里谈论一个模拟框架。