我已經看了一下其他問題,但沒有真正匹配我所尋找的內容...主要是因爲我不是100%確定它是什麼正在尋找!單元測試使用Moq的LINQ to SQL CRUD操作
基本上我正在研究一個新項目,我爲DB實體創建了我的抽象層,並將DAC設置爲存儲庫。我想用單元測試此與模仿對象,但我已經打了帶有CRUD(特別是C)的操作,我的單元測試類智力牆:
[TestClass]
public class RepositoryTest
{
private Mock<IPersonRepository> _repository;
private IList<IPerson> _personStore;
[TestInitialize()]
public void Initialize()
{
_personStore= new List<IPerson>() {
new Person() { Name = "Paul" },
new Person() { Name = "John" },
new Person() { Name = "Bob" },
new Person() { Name = "Bill" },
};
_repository = new Mock<IPersonRepository>();
_repository.Setup(r => r.Entirely()).Returns(_personStore.AsQueryable());
}
[TestCleanup()]
public void Cleanup()
{
_personStore.Clear();
}
[TestMethod()]
public void Can_Query_Repository()
{
IEnumerable<IPerson> people = _repository.Object.Entirely();
Assert.IsTrue(people.Count() == 4);
Assert.IsTrue(people.ElementAt(0).Name == "Paul");
Assert.IsTrue(people.ElementAt(1).Name == "John");
Assert.IsTrue(people.ElementAt(2).Name == "Bob");
Assert.IsTrue(people.ElementAt(3).Name == "Bill");
}
[TestMethod()]
public void Can_Add_Person()
{
IPerson newPerson = new Person() { Name = "Steve" };
_repository.Setup(r => r.Create(newPerson));
// all this Create method does in the repository is InsertOnSubmit(IPerson)
// then SubmitChanges on the data context
_repository.Object.Create(newPerson);
IEnumerable<IPerson> people = _repository.Object.Entirely();
Assert.IsTrue(people.Count() == 5);
}
}
我Can_Query_Repository方法是成功的,但是Can_Add_Person方法失敗斷言。現在,我需要做:
- 設置Mock存儲庫的.Create方法以將該元素添加到_personStore?
- 做類似的事嗎?
- 放棄所有希望,因爲我想達到的目標是不可能的,我做的一切都是錯誤的!
一如既往,任何幫助/建議表示讚賞!
只是一個快速的評論來證明爲什麼我的存儲庫返回方法是完全()。我的存儲庫名稱是AllPeople,所以我可以在AllPeople.WhereAgeIs,AllPeople.WhereDOBIs和AllPeople.Entirely。 –
您應該測試如果您正在模擬庫接口中添加/保存方法,而不是計數。 –
你的意思是.Verify()方法嗎?我剛剛嘗試過,測試成功運行(如果我刪除了。Count()檢查)......這是什麼意思,這是否檢查方法的功能工作? –