Skip to content

Instantly share code, notes, and snippets.

@plioi
Created January 27, 2016 00:38
Show Gist options
  • Save plioi/043458bf30be1d96d884 to your computer and use it in GitHub Desktop.
Save plioi/043458bf30be1d96d884 to your computer and use it in GitHub Desktop.
public class AutoFixtureParameterSource : ParameterSource
{
public IEnumerable<object[]> GetParameters(MethodInfo method)
{
// Produces a randomly-populated object for each
// parameter declared on the test method, using
// a Fixture that has our customizations.
var fixture = new Fixture();
CustomizeAutoFixture(fixture);
var specimenContext = new SpecimenContext(fixture);
var allEntitiesAttribute =
method.GetCustomAttributes<AllEntities>(true).SingleOrDefault();
if (allEntitiesAttribute != null)
{
return typeof(Entity).Assembly.GetTypes()
.Where(t => t.IsSubclassOf(typeof(Entity)))
.Where(t => !t.IsAbstract)
.Except(allEntitiesAttribute.Except)
.Select(entityType => new[] { specimenContext.Resolve(entityType) })
.ToArray();
}
var parameterTypes = method.GetParameters().Select(x => x.ParameterType);
var arguments = parameterTypes.Select(specimenContext.Resolve).ToArray();
return new[] { arguments };
}
private static void CustomizeAutoFixture(Fixture fixture)
{
var propertyBuilders = typeof(PropertyBuilder)
.Assembly
.GetTypes()
.Where(t => !t.IsAbstract && typeof(ISpecimenBuilder).IsAssignableFrom(t))
.Select(Activator.CreateInstance)
.Cast<ISpecimenBuilder>();
foreach (var propertyBuilder in propertyBuilders)
fixture.Customizations.Add(propertyBuilder);
}
}
[AttributeUsage(AttributeTargets.Method)]
class AllEntities : Attribute
{
public AllEntities()
{
Except = new Type[] { };
}
public Type[] Except { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment