C# 使用moq模拟具有泛型参数的类型
我有以下接口。我不确定如何使用Moq模拟IRepository,因为T是通用的。我肯定有办法,但我没有通过这里或谷歌搜索找到任何东西。有人知道我怎样才能做到这一点吗 我对Moq还比较陌生,但我能看到花时间学习它的好处C# 使用moq模拟具有泛型参数的类型,c#,unit-testing,generics,moq,C#,Unit Testing,Generics,Moq,我有以下接口。我不确定如何使用Moq模拟IRepository,因为T是通用的。我肯定有办法,但我没有通过这里或谷歌搜索找到任何东西。有人知道我怎样才能做到这一点吗 我对Moq还比较陌生,但我能看到花时间学习它的好处 /// <summary> /// This is a marker interface that indicates that an /// Entity is an Aggregate Root. /// </summary&
/// <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();
}
//
///这是一个标记接口,指示
///实体是聚合根。
///
公共接口IAggregateRoot
{
}
///
///存储库合同。具有存储库的实体
///必须是IAggregateRoot类型,因为只有聚合根
///应该在DDD中有一个存储库。
///
///
公共接口IRepository,其中T:IAggregateRoot
{
T FindBy(int-id);
IList FindAll();
无效添加(T项);
消除无效(T项);
无效删除(int-id);
无效更新(T项);
无效提交();
void RollbackAllChanges();
}
我在测试中创建了一个虚拟的具体类,或者使用现有的实体类型
如果不创建具体的类,可能只需要经历100个循环就可以做到这一点,但我认为这不值得。您必须指定类型,据我所知,没有直接返回泛型类型项的方法
mock = new Mock<IRepository<string>>();
mock.Setup(x => x.FindAll()).Returns("abc");
mock=newmock();
mock.Setup(x=>x.FindAll()).Returns(“abc”);
不应该是什么问题:
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();
}
}
公共接口IAggregateRoot{}
类测试:IAggregateRoot{}
公共接口IRepository,其中T:IAggregateRoot
{
// ...
IList FindAll();
无效添加(T项);
// ...
}
班级计划
{
静态void Main(字符串[]参数)
{
//创建模拟
var m=新的最小起订量Mock();
//一些例子
m、 设置(r=>r.Add(Moq.It.IsAny());
m、 Setup(r=>r.FindAll()).Returns(newlist());
m、 VerifyAll();
}
}
确保具有虚拟类的程序集在AssemblyInfo.cs中具有[assembly:InternalsVisibleTo(“DynamicProxy Assembly2”)],并且该类至少是内部的