I have made a generic databuilder for unit test, because I got tired of implementing constructors and Build methods again and again. Does this obscure the beauty of the pattern (that I really DO love)?
Here is my generic builder (built in C# with 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;
}
}
And here is an example interface and its concrete builder that inherrits the generic one:
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;
}
}
The builder will construct a foo mock like this:
IFoo fooMock = new FooBuilder().WithBar(12).Build();
I would love to hear oppinions and suggestions for improvement.
EDIT (Eventraising example added):
public class FooBuilderWithEvent: GenericMockBuilder<IFoo>
{
public FooBuilderWithEvent RaiseEvent(FooEventArgs fooEventArgs)
{
base.ObjectMock.Raise(m => m.FooEvent += null, fooEventArgs);
return this;
}
}
Building Mock and raising event would look like this:
FooBuilderWithEvent fooBuilderWithEvent = new FooBuilderWithEvent();
IFoo fooMock = fooBuilderWithEvent.Build();
//Create testobject and prepare for event here
fooBuilderWithEvent.RaiseEvent(new FooEventArgs());
pros
cons
Don’t know why you are asking for Moq sample, because you already have all this code inside builder:
If lambdas and
mock.Objectcalls are confusing to you, try RhinoMocks:Also I have a question – how are you going to raise events with only mocked object instance?