3

我对 Visual Studio 2012 单元测试有疑问,更准确地说是代码覆盖率。这是一个目标代码:

var someDeals = allDeals
            .Where(i => i.Number != null && !i.Number.StartsWith(SomeString))
            .Select(i => new DealInfoDto
            {
                CurrentDebtAmount = i.CurrentDebtAmount,
                Date = i.Date,
                NextMonthlyPaymentDate = i.NextMonthlyPaymentDate,
                Number = i.Number,
                AccountNumber = i.AccountNumber,
            })
            .ToArray();

当我运行分析代码覆盖率时,它显示第二行 ( i.Number != null && !i.Number.StartsWith(SomeString)) 中的 lambda 表达式是部分接触区域,我无法获得 100% 的覆盖率。但我确信这个表达式被评估了(SELECT 里面的表达式是好的,所以 WHERE 里面的表达式是真的,这意味着 && 语句的两个部分都被触及了,我也检查了数据,我确定i.Number != nulland !i.Number.StartsWith(SomeString)

为什么这个块没有被覆盖?

PS我Where分成两个表情,一切都变好了。但它看起来很难看,最好只有一个Where

allDeals
    .Where(i => i.Number != null)
    .Where(i => !i.Number.StartsWith(CardAccountIdentifier))
4

1 回答 1

5

This question looks very similar to MSTest Shows Partial Code Coverage on Compound Boolean Expressions.

What I suspect is happening is that you are not testing the early fail path when i.Number is null.

If you remember && will only evaluate the second expression if the first was true. In your case I suspect (as you haven't mentioned how or what your tests are) that you do not have a test or scenario where there is an entry in your allDeals collection where i.Number is null.

于 2012-10-31T21:57:33.070 回答