Use moq to simulate a type with a common parameter

I have the following interfaces. I'm not sure how I can use Moq to mock IRepository due to the fact that T is shared. I am sure there is a way, but I did not find anything by browsing here or on Google. Does anyone know how I can achieve this?

I am new to Moq, but I see that you need time to learn it.

/// <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(); } 
+7
source share
3 answers

There should be no problems:

 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(); } } 
+11
source

I create a dummy concrete class in my tests or use the existing Entity type.

It may be possible by going through 100 hoops without creating a specific class, but I don't think it's worth it.

+3
source

You should describe types, as far as I know, there is no direct way to return typical typed elements.

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

All Articles