Kap*_*old 25 java unit-testing factory ruby-on-rails factory-bot
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
Run Code Online (Sandbox Code Playgroud)
如果我需要一个用户,可以直接打电话
test_user = Factory(:user, :admin => true)
Run Code Online (Sandbox Code Playgroud)
这将产生具有工厂原型中指定的所有属性的用户,除了我明确指定的admin属性.另请注意,电子邮件工厂方法每次调用时都会生成不同的电子邮件.
我认为为Java实现类似的东西应该很容易,但我不想重新发明轮子.
PS:我知道JMock和EasyMoc,但我不是在谈论一个模拟框架.
mgu*_*mon 21
我也找了一个类似于Factory Girl的Java,但从来没有找到类似它的东西.相反,我从头开始创建了一个解决方案.用于在Java中生成模型的工厂:Model Citizen.
受Factory Girl的启发,它使用字段注释来设置模型的默认值,这是wiki的一个简单示例:
@Blueprint(Car.class)
public class CarBlueprint {
@Default
String make = "car make";
@Default
String manufacturer = "car manufacturer";
@Default
Integer mileage = 100;
@Default
Map status = new HashMap();
}
Run Code Online (Sandbox Code Playgroud)
这将是汽车模型的蓝图.这被注册到ModelFactory中,而新实例可以创建如下:
ModelFactory modelFactory = new ModelFactory();
modelFactory.registerBlueprint( CarBlueprint.class );
Car car = modelFactory.createModel(Car.class);
Run Code Online (Sandbox Code Playgroud)
您可以通过传入Car实例而不是Class并根据需要设置值来覆盖Car模型的值:
Car car = new Car();
car.setMake( "mustang" );
car = modelFactory.createModel( car );
Run Code Online (Sandbox Code Playgroud)
该维基具有更复杂的例子(如使用@Mapped几更花俏)和细节.
一个可能的库是Usurper.
但是,如果要指定要创建的对象的属性,那么Java的静态类型会使框架变得毫无意义.您必须将属性名称指定为字符串,以便框架可以使用反射或Java Bean内省查找属性访问器.这将使重构变得更加困难.
只是新建对象并调用它们的方法要简单得多.如果要在测试中避免大量样板代码,Test Data Builder模式可以提供帮助.