lundi 31 octobre 2016

Mock method with generic type

I have a test that find all class that inherited from BaseClass. BaseClass has a property with a method that use generics:

abstract class BaseClass 
{
   public MyTools Tools { get; set;}

   public abstract List<TEntity> GetAll();

   public virtual IList<TEntity> Convert<TEntity, TEntityOther>() 
   {
       //...
   }
}

class MyTools 
{
   T List<T>();    
}

I need to mock the T List<T>() method. The method is used in Create method. For example:

class MyClass: BaseClass<MyEntity>
{
    public override List<MyEntity> GetAll()
    {
        var x = this.MyTools.List<SomeClass>();

        return this.Convert<MyEntity, SomeClass>(x);
    }
}

I don't know what type is used within GetAll to call List method.

This is my test:

var xobjects = this.GetTypeInNamespace(myAssembly, typeof(BaseClass<>));

foreach(var obj in xobjects) 
{
   var myTools  = new Mock<MyTools>();

   //here is my problem
   myTools.Setup(x => x.List< ANY >()).Returns(new List< ANY >());

   var iobj = this.CreateInstance(obj);

   iobj.MyTools = myTools.Object;  

   var result = iobj.GetType().GetMethod("GetAll").Invoke(iobj, null);

   ((ICollection)result).Count.Should().Be(0);
}

Aucun commentaire:

Enregistrer un commentaire