【发布时间】:2016-01-15 10:38:04
【问题描述】:
我正在尝试编写单元测试。这是我第一次使用存储库和依赖注入来执行此操作。
我的单元测试如下:
[TestClass()]
public class PersonRepositoryTests
{
Mock<PersonRepository> persoonRepository;
IEnumerable<Person> personen;
[TestInitialize()]
public void Initialize()
{
persoonRepository = new Moq.Mock<PersonRepository >();
personen = new List<Person>() { new Person { ID = 1, Name = "Bart Schelkens", GewerkteDagen = 200, Leeftijd = 52, Type = "1" },
new Person { ID = 2, Name = "Yoram Kerckhofs", GewerkteDagen = 190, Leeftijd = 52, Type = "1" }};
persoonRepository.Setup(x => x.GetAll()).Returns(personen);
}
[TestMethod()]
public void GetAll()
{
var result = persoonRepository.Object.GetAll();
}
}
我的仓库:
public class PersonRepository
{
DatabaseContext DbContext { get; }
public PersonRepository(DatabaseContext dbContext)
{
this.DbContext = dbContext;
}
public virtual IEnumerable<Person> GetAll()
{
return DbContext.Persons.ToList();
}
}
现在当我运行测试时,我收到以下错误:
"无法实例化类的代理:CoBen.Dossier.DataAccess.Repository.PersonRepository。 找不到无参数构造函数。”
所以我做错了什么,但我没有看到。 谁能帮帮我?
【问题讨论】:
-
阅读错误信息...
-
@Steve:我知道它在说什么,我只是没有成功添加数据库上下文
-
请记住,当您模拟存储库时,存储库中的代码永远不会被调用,因为模拟“拦截”调用并返回您指定的值。因此,您可以将存储库方法提取到接口并模拟它。
标签: c# unit-testing dependency-injection mocking repository