简体   繁体   English

Moq无法模拟没有特定泛型的方法

[英]Moq can not mock a method without specific generic type

I have a test that find all class that inherited from BaseClass . 我有一个测试,查找从BaseClass继承的所有类。 BaseClass has a property with a method that use generics: BaseClass具有一个属性,该属性具有使用泛型的方法:

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

   public abstract List<TEntity> GetAll();

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

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

Then, I need to mock the T List<T>() method. 然后,我需要模拟T List<T>()方法。 The method is used in Create method. 该方法用于Create方法。 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. 我不知道在GetAll使用什么类型来调用List方法。

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);
}

How I can setup the method List <T> for any T? 如何为任何T设置方法List <T>

I don't know what type is T and I do not care what type it is. 我不知道T是什么类型,也不在乎它是什么类型。

我知道这个问题It.IsAnyType 3年的历史了,但是由于moq 4.13 ,可以为通用类型匹配指定It.IsAnyType

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM