2012-03-29 82 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"); 
相關問題