这种方法能达到100%的代码覆盖率吗?

Can this method reach 100% code coverage?

我有以下方法:

public static async Task<bool> CreateIfNotExistsAsync(
    this ISegment segment, 
    CancellationToken cancellationToken)
{
    Requires.ArgNotNull(segment, nameof(segment));

    try
    {
        await segment.CreateAsync(cancellationToken);
        return true;
    }
    catch (Exception error)
    {
        if (error.CanSuppress() && !cancellationToken.IsCancellationRequested)
        {
            var status = await segment.GetStatusAsync(cancellationToken);
            if (status.Exists)
            {
                return false;
            }
        }

        throw;
    }
}

...为此我编写了应该涵盖所有块的测试。然而;代码覆盖率结果(在 Visual Studio 2015 更新 3 中)显示有两个块没有被覆盖:

我认为这与在 catch 块中为 await 生成的代码有关,所以我尝试像这样重写方法:

public static async Task<bool> CreateIfNotExistsAsync(
    this ISegment segment, 
    CancellationToken cancellationToken)
{
    Requires.ArgNotNull(segment, nameof(segment));

    ExceptionDispatchInfo capturedError;

    try
    {
        await segment.CreateAsync(cancellationToken);
        return true;
    }
    catch (Exception error)
    {
        if (error.CanSuppress() && !cancellationToken.IsCancellationRequested)
        {
            capturedError = ExceptionDispatchInfo.Capture(error);
        }
        else
        {
            throw;
        }
    }

    var status = await segment.GetStatusAsync(cancellationToken);
    if (!status.Exists)
    {
        capturedError.Throw();
    }

    return false;
}

但是,还有一个区块没有被覆盖:

是否可以重写此方法,使其完全覆盖?


这是我的相关测试:

[TestMethod]
public async Task Create_if_not_exists_returns_true_when_create_succeed()
{
    var mock = new Mock<ISegment>();
    Assert.IsTrue(await mock.Object.CreateIfNotExistsAsync(default(CancellationToken)));
    mock.Verify(_ => _.CreateAsync(It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task Create_if_not_exists_throws_when_create_throws_and_cancellation_is_requested()
{
    var mock = new Mock<ISegment>();
    var exception = new Exception();

    mock.Setup(_ => _.CreateAsync(It.IsAny<CancellationToken>())).Throws(exception);

    try
    {
        await mock.Object.CreateIfNotExistsAsync(new CancellationToken(true));
        Assert.Fail();
    }
    catch (Exception caught)
    {
        Assert.AreSame(exception, caught);
    }

    mock.Verify(_ => _.CreateAsync(It.IsAny<CancellationToken>()), Times.Once);
    mock.Verify(_ => _.GetStatusAsync(It.IsAny<CancellationToken>()), Times.Never);
}

[TestMethod]
public async Task Create_if_not_exists_throws_when_create_throws_non_suppressable_exception()
{
    var mock = new Mock<ISegment>();
    var exception = new OutOfMemoryException();

    mock.Setup(_ => _.CreateAsync(It.IsAny<CancellationToken>())).Throws(exception);

    try
    {
        await mock.Object.CreateIfNotExistsAsync(default(CancellationToken));
        Assert.Fail();
    }
    catch (Exception caught)
    {
        Assert.AreSame(exception, caught);
    }

    mock.Verify(_ => _.CreateAsync(It.IsAny<CancellationToken>()), Times.Once);
    mock.Verify(_ => _.GetStatusAsync(It.IsAny<CancellationToken>()), Times.Never);
}

[TestMethod]
public async Task Create_if_not_exists_throws_when_create_throws_and_status_says_segment_doesnt_exists()
{
    var mock = new Mock<ISegment>();
    var exception = new Exception();

    mock.Setup(_ => _.CreateAsync(It.IsAny<CancellationToken>())).Throws(exception);
    mock.Setup(_ => _.GetStatusAsync(It.IsAny<CancellationToken>()))
        .ReturnsAsync(new SegmentStatus(false, false, null, 0));

    try
    {
        await mock.Object.CreateIfNotExistsAsync(default(CancellationToken));
        Assert.Fail();
    }
    catch (Exception caught)
    {
        Assert.AreSame(exception, caught);
    }

    mock.Verify(_ => _.CreateAsync(It.IsAny<CancellationToken>()), Times.Once);
    mock.Verify(_ => _.GetStatusAsync(It.IsAny<CancellationToken>()), Times.Once);
}

[TestMethod]
public async Task Create_if_not_exists_returns_false_when_create_throws_and_status_says_segment_exists()
{
    var mock = new Mock<ISegment>();

    mock.Setup(_ => _.CreateAsync(It.IsAny<CancellationToken>())).Throws<Exception>();
    mock.Setup(_ => _.GetStatusAsync(It.IsAny<CancellationToken>()))
        .ReturnsAsync(new SegmentStatus(true, false, null, 0));

    Assert.IsFalse(await mock.Object.CreateIfNotExistsAsync(default(CancellationToken)));

    mock.Verify(_ => _.CreateAsync(It.IsAny<CancellationToken>()), Times.Once);
    mock.Verify(_ => _.GetStatusAsync(It.IsAny<CancellationToken>()), Times.Once);
}

这是CanSuppress逻辑:

private static readonly Exception[] EmptyArray = new Exception[0];

/// <summary>
///     Determines whether an <see cref="Exception"/> can be suppressed.
/// </summary>
/// <param name="exception">
///     The <see cref="Exception"/> to test.
/// </param>
/// <returns>
///     <c>true</c> when <paramref name="exception"/> can be suppressed; otherwise <c>false</c>.
/// </returns>
/// <remarks>
/// <para>
///     We do not want to suppress <see cref="OutOfMemoryException"/> or <see cref="ThreadAbortException"/> 
///     or any exception derived from them (except for <see cref="InsufficientMemoryException"/>, which we
///     do allow suppression of).
/// </para>
/// <para>
///     An exception that is otherwise suppressable is not considered suppressable when it has a nested 
///     non-suppressable exception.
/// </para>
/// </remarks>
public static bool CanSuppress(this Exception exception)
{
    foreach (var e in exception.DescendantsAndSelf())
    {
        if ((e is OutOfMemoryException && !(e is InsufficientMemoryException)) ||
            e is ThreadAbortException)
        {
            return false;
        }
    }

    return true;
}

private static IEnumerable<Exception> DescendantsAndSelf(this Exception exception)
{
    if (exception != null)
    {
        yield return exception;

        foreach (var child in exception.Children().SelectMany(ExceptionExtensions.DescendantsAndSelf))
        {
            yield return child;
        }
    }
}

private static IEnumerable<Exception> Children(this Exception parent)
{
    DebugAssumes.ArgNotNull(parent, nameof(parent));

    var aggregate = parent as AggregateException;

    if (aggregate != null)
    {
        return aggregate.InnerExceptions;
    }
    else if (parent.InnerException != null)
    {
        return new[] { parent.InnerException };
    }
    else
    {
        return ExceptionExtensions.EmptyArray;
    }
}

好的 - 经过大量挖掘 - 罪魁祸首是 await segment.GetStatusAsync(cancellationToken)。这会导致代码覆盖率将 throw 视为 部分 覆盖。用非异步方法替换该行正确显示 throw 被覆盖

现在,async 在内部创建了一个状态机。您可以在代码覆盖率中看到这一点,它找到了一个名为

的方法

<CreateIfNotExistsAsync>d__1.MoveNext:

在生成的IL中,这个弹出给我:

IL_01B4:  ldfld       MyExtensions+<CreateIfNotExistsAsync>d__1.<>s__1
IL_01B9:  isinst      System.Exception
IL_01BE:  stloc.s     0A 
IL_01C0:  ldloc.s     0A 
IL_01C2:  brtrue.s    IL_01CB
IL_01C4:  ldarg.0     
IL_01C5:  ldfld       MyExtensions+<CreateIfNotExistsAsync>d__1.<>s__1
IL_01CA:  throw       
IL_01CB:  ldloc.s     0A 
IL_01CD:  call        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture
IL_01D2:  callvirt    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw

这里有两种方式抛出异常:

IL_01B4:  ldfld       MyExtensions+<CreateIfNotExistsAsync>d__1.<>s__1
IL_01B9:  isinst      System.Exception
IL_01BE:  stloc.s     0A 
IL_01C0:  ldloc.s     0A 
IL_01C2:  brtrue.s    IL_01CB
IL_01C4:  ldarg.0     
IL_01C5:  ldfld       MyExtensions+<CreateIfNotExistsAsync>d__1.<>s__1
IL_01CA:  throw       

这实际上是从 s__1 中获取字段,并检查它是否是 Exception 类型。例如:machine.state1 is Exception

然后,如果为真,则分支到 IL_01CB

IL_01CB:  ldloc.s     0A 
IL_01CD:  call        System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture
IL_01D2:  callvirt    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw

抛出异常。但是,如果它是 false,它会调用 throw OpCode。

这意味着 throw 被翻译成两个可能的路径,其中只有一个被执行。我不确定在 C# 中 IL_01B9: isinst System.Exception 是否可能为假,但我可能是错的 - 或者在 .NET 中通常是可能的。

坏消息是,我没有解决方案。我的建议是:将代码覆盖率作为 指南,因为即使 100% 的覆盖率也不意味着代码没有错误。话虽如此,您可以从逻辑上推断 throw 被标记为 'partially covered' 与被完全覆盖

本质上相同