[英]Use moq to mock a type with generic parameter
我有以下接口。 由於T是通用的,我不確定如何使用Moq來模擬IRepository。 我確定有辦法,但我沒有找到任何東西通過搜索這里或谷歌。 有誰知道我怎么能做到這一點?
我對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();
}
根本不應該是一個問題:
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();
}
}
我在測試中創建了一個偽具體類 - 或者使用現有的實體類型。
有可能在沒有創建具體課程的情況下完成100個籃球,但我認為這不值得。
你必須使用speficy類型,據我所知,沒有直接的方式返回泛型類型的項目。
mock = new Mock<IRepository<string>>();
mock.Setup(x => x.FindAll()).Returns("abc");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.