创建对象层次结构进行测试 [英] Create object hierarchy for test

查看:71
本文介绍了创建对象层次结构进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我构建了一个测试驱动的应用程序,它将平面文件分类为父子层次结构.现在,我想为自己的排序创建一个非常通用的测试.为此,我想生成一些测试数据,然后对它们进行排序.

I building a test-driven application that will sort a flat file into a parent-child-hierarchy. And now I want to create a pretty generic test for my own sorting. For that I want to generate some test data, which I then sort.

将要排序的对象看起来像这样:

The object that will be sorted will look something like this:

public interface IHierarchicalUnitWithChildren
{
    string Id { get; }
    string ParentId { get; }
    IList<IHierarchicalUnitWithChildren> Children { get; set; }
}

但是我不想自己创建测试对象.我希望这是通过代码生成的,例如:

But I don't want to create the test-object myself. I want this to be generated by code, as such:

        _items = new List<IHierarchicalUnitWithChildren>();
        Random random = new Random();

        for (int i = 1; i < 1000; i++)
        {
            var item = new HierarchicalUnitMock()
            {
                Oid = i.ToString(),
                Children = new List<IHierarchicalUnit>(),
            };

            // We need a couple of roots.
            if (i%100 != 0)
            {
                item.Poid = random.Next(1, 100).ToString();
            }

            _items.Add(item);
        }

我可以轻松生成一千个项目,但我还需要给他们一个有效的父项.如何确保我正在创建一个有效的结构,其中有几个根并且所有子代都有有效的父母.

I can easily generate a thousand items, but I also need to give them a valid parent. How can I make sure that I'm creating a valid structure, where I have a couple of roots and all children have parents that are valid.

任何物品都不应具有其自身的子代(或孙子代)的父代,从而使其成为无限层级.

No item should have a parent that is a child (or grandchild) of itself and thus making it an infinite hierachy.

还是我在想这一切错了?测试应该始终具有静态数据吗?

Or am I thinking about it all wrong? Should a test always have static data?

更新:

有什么办法可以始终生成相同的数据的智能循环吗?这样测试用例总是相同的吗?

Is there any way to do this with a smart loop, that always generate the same data? So that the test-case always will be the same?

推荐答案

在测试中随机生成的数据不是一个好主意.您无法保证每次的测试条件都相同,也无法保证涵盖所有可能的情况.

Randomly live-generated data in tests is not a good idea. there's no way you can guarantee the test conditions will be the same every time, and no guarantee that you cover every possible scenario.

相反:

考虑一下代码的功能,必要时将其分解为伪代码,然后尝试提出可能会破坏它的方案.专门设置导致这些情况的测试数据.

Think about what your code does, break it down into pseudo code if you have to, and try to come up with scenarios that could break it. make your test data set specifically to cause these conditions.

这篇关于创建对象层次结构进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆