jeudi 23 juillet 2015

Reflection on mocked data in unit tests (Rhino)

I have some code that selects a property using reflection. It works fine but I can't unit test it. Apparently, the mock that it creates does not have any properties. Can anyone tell me how to get the property from a Mocked object using reflection? (Or explain why it would not be possible?)

var target = To.GetType().GetProperties()
    .Single(x => typeof(IRepository<T>).IsAssignableFrom(x.PropertyType))
    .GetValue(To) as IRepository<T>;

I'm using this for a copy class which allows to copy data for any entity type and expects a UnitOfWork that contains a IRepository where T is the type that you want to copy.

public class TableCopier<T> : ICopier where T : EntityBase
{
    public IUnitOfWork From { get; set; }
    public IUnitOfWork To { get; set; }

    public virtual int Copy(IProgressReporter progres = null)
    {
        lock (this)
        {
            var target = To.GetType().GetProperties()
                .Single(x => typeof(IRepository<T>).IsAssignableFrom(x.PropertyType))
                .GetValue(To) as IRepository<T>;
            //...
        }
    }
}

The Unit of Work looks like this:

public interface IUnitOfWork
{
    IRepository<Parameter> ParameterRepository { get; }
    IRepository<Company> CompanyRepository { get; }
    IRepository<CompanyAccountancynumber> CompanyAccountancynumberRepository { get; }
    //...

And finally the unit test:

    [Test]
    public void DefaultCopy()
    {
        // (removed some code)
        var to = MockRepository.GenerateStrictMock<IUnitOfWork>();

        var target = MockRepository.GenerateStrictMock<IRepository<CompanyDataset>>();
        to.Stub(x => x.CompanyDatasetRepository).Return(target);
        var inserted = new List<CompanyDataset>();
        target.Stub(x => x.BulkInsert(null))
            .IgnoreArguments()
            .WhenCalled(x => inserted.AddRange(x.Arguments[0] as IEnumerable<CompanyDataset>));

        //ACT
        var copier = new TableCopier<CompanyDataset>() as ICopier;
        copier.Copy(from, to, map, log, null, CancellationToken.None );





Aucun commentaire:

Enregistrer un commentaire