我正在嘗試編寫單元測試。這是我第一次使用存儲庫和依賴注入來做這件事。使用mocks的單元測試代碼庫
我的單元測試看起來如下:
[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();
}
}
現在,當我跑我的測試,我得到以下錯誤:
「無法實例的代理class:CoBen.Dossier.DataAccess.Repository.PersonRepository。 找不到無參數的構造函數。「
所以我做錯了什麼,但我沒有看到它。 任何人都可以幫助我嗎?
閱讀錯誤消息... – Steve
@Steve:我知道它說了什麼,我只是沒有成功添加數據庫上下文 –
請記住,當您嘲笑版本庫時,版本庫中的代碼永遠不會被調用,因爲模擬「攔截」呼叫並返回您指定的值。所以你可以將存儲庫方法提取到一個接口,然後模擬它。 – stuartd