gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:06:43 25 4
gpt4 key购买 nike

我有一个函数,它遍历父对象列表并在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com