首页 > 解决方案 > 分行覆盖问题

问题描述

我很纠结为什么我在这段代码的测试中没有得到 100% 的测试分支覆盖率:

    public List<ReturnItem> FilterItems(List<Items> items)
    {
        if (items== null || !items.Any())
        {
            throw new ArgumentException("No items to filter");
        }

        var newItems = new List<NewItem>();

        foreach (var item in items)
        {
            if (item.Tracking.MidStateDate != null)
            {
                if (orderLine.Tracking.EndStateDate.GetValueOrDefault() < orderLine.Tracking.MidStateDate)
                {
                    var newItem = new NewItem(item);
                    newItem.MidStateDate = item.Tracking.MidStateDate.Value;
                    newItems.Add(newItem);
                }
            }
        }

        return newItems;
    }

我有以下测试:

我无法让分支覆盖率测试达到 100%。这让我觉得我错过了一些东西。我删除了大部分代码,发现问题与这个条件有关if (orderLine.Tracking.EndStateDate.GetValueOrDefault() < orderLine.Tracking.MidStateDate)

任何人都可以建议我可以添加的任何其他单元测试来处理分支覆盖问题吗?

标签: c#.netunit-testingcode-coverage

解决方案


就像我回复@juharr 一样,我有一个脑电波。

问题在于代码在有问题的条件中的可空日期时间不明确。

if (orderLine.Tracking.EndStateDate.GetValueOrDefault() < orderLine.Tracking.MidStateDate)

^ 导致问题

if (orderLine.Tracking.EndStateDate.GetValueOrDefault() < orderLine.Tracking.MidStateDate.Value)

^ 工作!


推荐阅读