Skip to content

Instantly share code, notes, and snippets.

@dejanvasic85
Created May 19, 2015 06:49
Show Gist options
  • Save dejanvasic85/3d35370190818babc740 to your computer and use it in GitHub Desktop.
Save dejanvasic85/3d35370190818babc740 to your computer and use it in GitHub Desktop.
Nice builder pattern to for building mock objects using Actions
internal class MockBuilder<TBuilder, TMock>
where TBuilder : MockBuilder<TBuilder, TMock>, new()
where TMock : class, new()
{
private IList<Action<TMock>> _buildSteps;
protected MockBuilder()
{
_buildSteps = Enumerable.Empty<Action<TMock>>().ToList();
}
protected TBuilder WithBuildStep(params Action<TMock>[] newBuildSteps)
{
var builder = new TBuilder { _buildSteps = _buildSteps.AddRange(newBuildSteps).ToList() };
return builder;
}
public TMock Build()
{
var mockObject = new TMock();
foreach (var action in _buildSteps)
{
action(mockObject);
}
return mockObject;
}
}
internal class PersonMockBuilder : MockBuilder<PersonMockBuilder, Simple>
{
public PersonMockBuilder WithName(string title, string firstName, string surname)
{
return WithBuildStep(p => p.Title = title)
.WithBuildStep(p => p.FirstName = firstName)
.WithBuildStep(p => p.Surname = surname);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment