Create object hierarchy for test

笑着哭i 提交于 2019-12-24 11:34:23

问题


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?

UPDATE:

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?


回答1:


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.

Instead:

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.



来源:https://stackoverflow.com/questions/32901743/create-object-hierarchy-for-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!