我已经看了一下其他问题,但没有真正匹配我所寻找的内容...主要是因为我不是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()检查)......这是什么意思,这是否检查方法的功能工作? –