我有一个函数遍历父对象的列表,并获取for-each循环中每个父对象的子对象。要获取子对象列表,该函数会调用另一个函数。这里是功能:如何测试嵌套的foreach循环?
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进行嘲弄。
offtopic:你永远添加'parentObject'到'parentObjects'。你在'parentObjects'上调用'Children'而不是新创建的'parentObject'。所以你的代码根本不能编译(除非你有'Children'属性的'List'实现)。 –
MarcinJuraszek
你模拟'_dbRepository'。 –