分支机构覆盖问题

时间:2020-09-16 16:34:44

标签: c# .net unit-testing code-coverage

我很想知道为什么我对这段代码的测试没有得到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;
    }

我已经进行了以下测试:

  • NoItems();
  • HasItems_NullTracking();
  • HasItems_NoTracking();
  • HasItems_HasTracking_NoMidStateDate();
  • HasItems_HasTracking_HasMidStateDate_NullEndStateDate();
  • HasItems_HasTracking_HasMidStateDate_SmallerEndStateDate();
  • HasItems_HasTracking_HasMidStateDate_EndStateDateIsEqual();
  • HasItems_HasTracking_HasMidStateDate_LargerEndStateDate();
  • HasItems_HasTracking_HasMidStateDate_MixedState();

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

有人可以建议我添加其他任何单元测试来解决分支覆盖问题吗?

1 个答案:

答案 0 :(得分:1)

就像我回复@juharr一样,我脑子里充满了头脑。

问题出在有问题的条件中,代码没有用可空的datetime明确显示。

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

^引起了问题

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

^有效!

相关问题