我已经为单元测试制作了一个通用数据构建器,因为我厌倦了一次又一次地实现构造函数和 Build 方法。这是否掩盖了图案的美丽(我真的很喜欢)?
这是我的通用构建器(在 C# 中使用 Moq 构建):
public class GenericMockBuilder<T> where T: class
{
private readonly Mock<T> _objectMock = new Mock<T>();
protected Mock<T> ObjectMock
{
get { return _objectMock; }
}
public T Build()
{
return _objectMock.Object;
}
}
这是一个示例接口及其继承通用接口的具体构建器:
public interface IFoo
{
int Bar();
}
public class FooBuilder: GenericMockBuilder<IFoo>
{
public FooBuilder WithBar(int barValue)
{
base.ObjectMock.Setup(x => x.Bar()).Returns(barValue);
return this;
}
}
构建器将像这样构造一个 foo 模拟:
IFoo fooMock = new FooBuilder().WithBar(12).Build();
我很想听听意见和改进建议。
编辑(添加了 Eventraising 示例):
public class FooBuilderWithEvent: GenericMockBuilder<IFoo>
{
public FooBuilderWithEvent RaiseEvent(FooEventArgs fooEventArgs)
{
base.ObjectMock.Raise(m => m.FooEvent += null, fooEventArgs);
return this;
}
}
Building Mock and raise 事件如下所示:
FooBuilderWithEvent fooBuilderWithEvent = new FooBuilderWithEvent();
IFoo fooMock = fooBuilderWithEvent.Build();
//Create testobject and prepare for event here
fooBuilderWithEvent.RaiseEvent(new FooEventArgs());