繁体   English   中英

使用Moq对LINQ to SQL CRUD操作进行单元测试

[英]Unit testing LINQ to SQL CRUD operations using Moq

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

基本上我现在正在开发一个新项目,我已经为数据库实体创建了抽象层,并将DAC设置为存储库。 我想用Mock对象对它进行单元测试,但是我已经用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. 放弃所有希望,因为我想要达到的目标是不可能的,而且我做错了!

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

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

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

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

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

第二个。 或者,如果要验证已在存储库集合中添加的实际对象,则可以在模拟上使用.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);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM