I'm using the Bogus library to mock up some data for testing.
This is my main method demonstrating how the faking service should be used:
class Program
{
static void Main(string[] args)
{
IFakerService r = new FakerService();
var dogs = r.Generate<Dog>(10);
var customers = r.Generate<Customer>(10);
var cats = r.Generate<Cat>(10);
}
}
A Dog class looks like:
public class Dog
{
public string Name { get; set; }
public bool IsGoodBoy => true;
}
My interface simply defines the only method the service should expose:
public interface IFakerService
{
IEnumerable<T> Generate<T>(int count) where T : class;
}
And the service itself:
public class FakerService : IFakerService
{
// Can we do better than <Type, object> ?
private Dictionary<Type, object> _fakers;
public FakerService()
{
_fakers = InitialiseFakers();
}
public IEnumerable<T> Generate<T>(int count) where T : class
{
var faker = GetFaker<T>();
return faker.Generate(count);
}
// Types which can be faked are registered here
private Dictionary<Type, object> InitialiseFakers()
{
return new Dictionary<Type, object>()
{
{typeof(Dog), new DogFaker().GetFaker()},
{typeof(Cat), new CatFaker().GetFaker()},
{typeof(Customer), new CustomerFaker().GetFaker()}
};
}
private Faker<T> GetFaker<T>() where T : class
{
if (!_fakers.ContainsKey(typeof(T)))
{
throw new ArgumentException($"Type: {typeof(T).FullName} not registered with FakerService");
}
var faker = (Faker<T>)_fakers[typeof(T)];
return faker;
}
}
The interface for Faker objects:
public interface IFaker<T> where T : class
{
Faker<T> GetFaker();
}
And one of the implementations:
public class DogFaker : IFaker<Dog>
{
public Faker<Dog> GetFaker()
{
return new Faker<Dog>()
.RuleFor(dog => dog.Name, f => f.Name.FirstName(Name.Gender.Male))
.RuleFor(dog => dog.IsGoodBoy, f => f.Random.Bool());
}
}
Overall I'm quite happy with how it looks - the parts that I was wondering if I could improve on are:
private Dictionary<Type, object> _fakers;
...
return new Dictionary<Type, object>()
{
{typeof(Dog), new DogFaker().GetFaker()}
}
...
var faker = (Faker<T>)_fakers[typeof(T)];
Any advice is appreciated!
Faker
APIs when you need them. I'm not sure how this service helps. \$\endgroup\$ – t3chb0t Nov 1 '18 at 15:45