使用Moq对LINQ to SQL CRUD操作进行unit testing

我已经浏览了其他问题,但没有什么能与我正在寻找的东西相提并论……主要是因为我并不是100%肯定我正在寻找什么!

基本上我目前正在开发一个新项目,我已经为数据库实体创建了抽象层,并将DAC设置为存储库。 我想用Mock对象对它进行unit testing,但是我已经用CRUD(特别是C)操作打了一个知识墙,我的unit testing类:

[TestClass] public class RepositoryTest { private Mock _repository; private IList _personStore; [TestInitialize()] public void Initialize() { _personStore= new List() { new Person() { Name = "Paul" }, new Person() { Name = "John" }, new Person() { Name = "Bob" }, new Person() { Name = "Bill" }, }; _repository = new Mock(); _repository.Setup(r => r.Entirely()).Returns(_personStore.AsQueryable()); } [TestCleanup()] public void Cleanup() { _personStore.Clear(); } [TestMethod()] public void Can_Query_Repository() { IEnumerable 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 people = _repository.Object.Entirely(); Assert.IsTrue(people.Count() == 5); } } 

我的Can_Query_Repository方法成功,但Can_Add_Person方法无法断言。 现在,我需要这样做:

  1. 设置Mock存储库的.Create方法以将元素添加到_personStore?
  2. 做其他类似的事情?
  3. 放弃所有的希望,因为我想要达到的目标是不可能的,而且我做错了!

一如既往,任何帮助/建议表示赞赏!

理想情况下,您会为这些进行一些集成测试,但如果您想对其进行unit testing,则可能有一些途径,包括原始问题的评论中未提及的途径。

第一个。 测试你的crud时,你可以使用.Verify来检查是否真的调用了Create方法。

 mock.Verify(foo => foo.Execute("ping")); 

使用Verify,您可以检查参数是否是某个类型的某个参数以及实际调用该方法的次数。

第二个。 或者,如果要validation已在存储库集合中添加的实际对象,可以执行的操作是在模拟上使用.Callback方法。

在您的测试中,创建一个列表,该列表将接收您创建的对象。 然后在您调用设置的同一行添加一个回调,它将在列表中插入创建的对象。

在断言中,您可以检查列表中的元素,包括它们的属性,以确保添加了正确的元素。

 var personsThatWereCreated = new List(); _repository.Setup(r => r.Create(newPerson)).Callback((Person p) => personsThatWereCreated.Add(p)); // test code // ... // Asserts Assert.AreEuqal(1, personsThatWereCreated.Count()); Assert.AreEqual("Bob", personsThatWereCreated.First().FirstName); 

在您的实际示例中,您可以创建人员,然后将其添加到设置中。 在这里使用回调方法没有用。

您还可以使用此技术增加变量以计算调用它的次数。