I'm trying to create a generic class that can build a Mock of a generic interface to assist me with various unit testing functions.
I need the built mock object to have all its DbSet<T> properties populated with TestDbSet<T> instances (TestDbSet<T> inherits from DbSet<T>).
For a specific example, given the interface:
public interface IAppointmentSchedulerContext
{
    DbSet<ServiceCenter> ServiceCenters { get; set; }
}
I would like to be able to have my TestDbContextBuilder class construct a mock instance where the ServiceCenters property is populated with an instance of a ServiceCenter<T>.
This is what I have so far:
public class TestDbContextBuilder<TDbContextInterface> where TDbContextInterface : class
{
    public TDbContextInterface Build()
    {
        var mock = new Mock<TDbContextInterface>();
        var dbSetProps = typeof(TDbContextInterface).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                    .Where(pi => pi.PropertyType.IsGenericType &&
                                                                 pi.PropertyType.GetGenericTypeDefinition() ==
                                                                 typeof(DbSet<>));
        //populate all the DbSet<TEntity> properties (in dbSetProps) on the mock with TestDbSet<TEntity> instances
        return mock.Object;
    }
}
If I were doing this statically, outside of the generic builder, I would just do this:
mock.SetupProperty(m=>m.ServiceCenters).Returns(new TestDbSet<ServiceCenter>());
But how do this dynamically, for all the DbSet<> properties on the generic TDbContextInterface interface?
 
Aucun commentaire:
Enregistrer un commentaire