Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.