简体   繁体   English

使用moq模拟具有泛型参数的类型

[英]Use moq to mock a type with generic parameter

I have the following interfaces. 我有以下接口。 I'm not sure how I can use Moq to mock up an IRepository due to the fact that T is generic. 由于T是通用的,我不确定如何使用Moq来模拟IRepository。 I'm sure there's a way, but I haven't found anything through searching through here or google. 我确定有办法,但我没有找到任何东西通过搜索这里或谷歌。 Does anybody know how I can achieve this? 有谁知道我怎么能做到这一点?

I'm fairly new to Moq, but can see the benefit of taking the time to learn it. 我对Moq很新,但可以看到花时间学习它的好处。

    /// <summary>
    /// This is a marker interface that indicates that an 
    /// Entity is an Aggregate Root.
    /// </summary>
    public interface IAggregateRoot
    {
    } 


/// <summary>
    /// Contract for Repositories. Entities that have repositories
    /// must be of type IAggregateRoot as only aggregate roots
    /// should have a repository in DDD.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public interface IRepository<T> where T : IAggregateRoot
    {
        T FindBy(int id);
        IList<T> FindAll();
        void Add(T item);
        void Remove(T item);
        void Remove(int id);
        void Update(T item);
        void Commit();
        void RollbackAllChanges();
    }

Shouldn't be a problem at all: 根本不应该是一个问题:

public interface IAggregateRoot { }

class Test : IAggregateRoot { }

public interface IRepository<T> where T : IAggregateRoot
{
    // ...
    IList<T> FindAll();
    void Add(T item);
    // ...
 }

class Program
{
    static void Main(string[] args)
    {
        // create Mock
        var m = new Moq.Mock<IRepository<Test>>();

        // some examples
        m.Setup(r => r.Add(Moq.It.IsAny<Test>()));
        m.Setup(r => r.FindAll()).Returns(new List<Test>());
        m.VerifyAll();
    }
}

I create a dummy concrete class in my tests - or use an existing Entity type. 我在测试中创建了一个伪具体类 - 或者使用现有的实体类型。

It might be possible to do it with going through 100 hoops without creating a concrete class, but I do not think it is worth it. 有可能在没有创建具体课程的情况下完成100个篮球,但我认为这不值得。

You have to speficy the types, as far as I know there is no direct way of returning generic typed items. 你必须使用speficy类型,据我所知,没有直接的方式返回泛型类型的项目。

mock = new Mock<IRepository<string>>();    
mock.Setup(x => x.FindAll()).Returns("abc");

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

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