2011-09-29 93 views
4

我已经看了一下其他问题,但没有真正匹配我所寻找的内容...主要是因为我不是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方法失败断言。现在,我需要做:

  1. 设置Mock存储库的.Create方法以将该元素添加到_personStore?
  2. 做类似的事吗?
  3. 放弃所有希望,因为我想达到的目标是不可能的,我做的一切都是错误的!

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

+0

只是一个快速的评论来证明为什么我的存储库返回方法是完全()。我的存储库名称是AllPeople,所以我可以在AllPeople.WhereAgeIs,AllPeople.WhereDOBIs和AllPeople.Entirely。 –

+1

您应该测试如果您正在模拟库接口中添加/保存方法,而不是计数。 –

+0

你的意思是.Verify()方法吗?我刚刚尝试过,测试成功运行(如果我删除了。Count()检查)......这是什么意思,这是否检查方法的功能工作? –

回答

6

理想你会做那些一些集成测试,但如果你想单元测试,有可能途径,包括未在原来的问题的意见中提到一个。

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

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

有了验证,可以确认的说法是有一定的说法,某种类型的和时代的方法实际上是叫号。

第二个。 或者,如果您想验证存储库集合中已添加的实际对象,则可以在模拟上使用.Callback方法。

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

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

var personsThatWereCreated = new List<Person>(); 

_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); 

在您的实际示例中授予您创建人员然后将其添加到设置中。在这里使用回调方法不会有用。

你也可以使用这种技术来增加一个变量来计算它被调用的次数。