c# - 如何对嵌套的 foreach 循环进行单元测试?

标签 c# unit-testing moq

我有一个函数,它可以迭代父对象列表,并在 for-each 循环中为每个父对象获取子对象。为了获取子对象的列表,该函数调用另一个函数。这是函数:

public IEnumerable<IParentObject> GetParentAndChildObjects()
{
    var parentObjects = new List<ParentObject>();

    foreach (var item in _dbRepository.GetParentObjects())
    {
        var parentObject = new ParentObject() { Id = item.ID, Name = item.Name };
        foreach (var subItem in _dbRepository.GetChildObjects(item.ID))
        {
            parentObjects.Children.Add(new ChildObject() { Id = subItem.ID, Name = subItem.Name });
        }
    }
    return parentObjects;
}

如何为此函数编写单元测试?我正在使用 Moq 进行模拟。

最佳答案

您可以使用的一种方法是以与私有(private)方法相同的方式测试内部循环。也就是说,您不这样做(至少不直接这样做)。

验证 GetParentAndChildObjects 返回的结果,而不是测试循环本身。

通过为 _dbRepository 指定测试替身,您可以完全控制插入到 parentObjects 列表中的对象的详细信息。因此,您的测试只能验证返回的对象列表是否符合预期。

Mark Seemann describes this approach well:

After having answered the question on when to use [stubs and when to use mocks], a couple of times, I arrived at this simple rule, based on the language of Command Query Separation (CQS):

  • Use Mocks for Commands

  • Use Stubs for Queries

This makes lots of sense, because Commands are all about side effects, and Mocks are all about Behaviour Verification: that is, that side effects occurred. Stubs, on the other hand, mainly exist to 'make happy noises', and one of the ways they have to do that, is to return data from dependencies, when return data is required.

关于c# - 如何对嵌套的 foreach 循环进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438259/

相关文章:

c# - 资源管理器 7 上的大表性能不佳

c++ - 是否可以将 MS 单元测试从 EXE 转发到 DLL?

unit-testing - 如何在单元测试中测试功能行为?

c# - 需要合并到 View 中的列表

c# - 你如何将 Html 转换为纯文本?

asp.net-mvc - 起订量中的验证()有多可靠?

unit-testing - 在哪里保存单元测试数据?

c# - 单元测试 MongoWriteExceptions

c# - .net core API 文件上传无法在 Azure 上运行

java - SetUp,初始化Junit测试