Skip to content

Instantly share code, notes, and snippets.

@JaykeOps
Created January 5, 2018 10:39
Show Gist options
  • Save JaykeOps/0f8ec61a3f379fdca04ca63df3998fb6 to your computer and use it in GitHub Desktop.
Save JaykeOps/0f8ec61a3f379fdca04ca63df3998fb6 to your computer and use it in GitHub Desktop.
Autofixture Custom SpecimenBuilder Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Kernel;
using Xunit;
namespace AutoFixtureSandbox.Tests
{
public class AutoFixtureLearningTests
{
[Fact]
public void CanCreateCustomRandomCarModel()
{
var fixture = new Fixture();
fixture.Customizations.Add(new CarSpecimenBuilder());
var car = fixture.Create<Car>();
Assert.True(car.Model == "M3" || car.Model == "V70" || car.Model == "R8");
}
}
public class Car
{
public Car(string model, string make, int productionYear)
{
if (model.Length >= 5)
throw new ArgumentException();
Model = model;
Make = make;
ProductionYear = productionYear;
}
public string Model { get; }
public string Make { get; }
public int ProductionYear { get; }
}
public class CarSpecimenBuilder : ISpecimenBuilder
{
private static Random randomizer = new Random();
private List<string> carModels = new List<string> {"M3", "V70", "R8"};
public object Create(object request, ISpecimenContext context)
{
var type = request as Type;
var propInfo = type?.GetProperty("Model");
if (!(propInfo is PropertyInfo))
return new NoSpecimen();
if (IsCarModelProperty(propInfo))
return new Car(RandomCarModel(), context.Create<string>(), context.Create<int>());
return new NoSpecimen();
}
private static bool IsCarModelProperty(PropertyInfo propertyInfo)
=> propertyInfo.Name.Contains("Model") && propertyInfo.PropertyType == typeof(string);
private string RandomCarModel()
{
var index = randomizer.Next(0, 2);
return carModels.ElementAt(index);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment