2012-03-29 30 views
7

के साथ एक प्रकार का नकल करने के लिए moq का उपयोग करें मेरे पास निम्न इंटरफेस हैं। मुझे यकीन नहीं है कि टी सामान्य है कि इस तथ्य के कारण मैं एक आईरिपोजिटरी का नकल करने के लिए मोक का उपयोग कैसे कर सकता हूं। मुझे यकीन है कि एक रास्ता है, लेकिन मुझे यहां या Google के माध्यम से खोज के माध्यम से कुछ भी नहीं मिला है। क्या कोई जानता है कि मैं इसे कैसे प्राप्त कर सकता हूं?जेनेरिक पैरामीटर

मैं मोक के लिए बिल्कुल नया हूं, लेकिन इसे सीखने के लिए समय निकालने का लाभ देख सकता हूं।

/// <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"); 
संबंधित मुद्दे