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

2024-04-07

我已经查看了其他问题,但没有什么真正符合我正在寻找的内容......主要是因为我不能 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. 放弃所有希望,因为我想要实现的目标是不可能的,而且我做的都是错的!

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


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

第一个。当测试你的 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);

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Moq 对 LINQ to SQL CRUD 操作进行单元测试 的相关文章

随机推荐