2012-03-29 77 views
7

我有以下接口。由于T是通用的,我不确定如何使用Moq来模拟IRepository。我确信有一种方法,但我没有通过在这里或谷歌搜索找到任何东西。有人知道我能做到吗?使用moq来模拟具有通用参数的类型

我对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(); 
    } 

回答

11

不应该在所有的问题:

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

我在我的测试中创建了一个虚拟混凝土类 - 或者使用了现有的实体类型。

通过100次篮球而不创造具体课程也许是可能的,但我认为这不值得。

2

你必须说明类型,据我所知没有直接的方式返回泛型类型的项目。

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