此方法可以达到100%的代码覆盖率吗?

时间:2016-11-04 12:10:45

标签: c# visual-studio asynchronous exception-handling 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 Update 3中)显示没有覆盖两个块:

Two blocks not covered

我认为这与在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;
}

但是,仍然有一个块未被覆盖:

Still not fully covered

是否可以重写此方法以便完全覆盖它?

以下是我的相关测试:

[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;
    }
}

1 个答案:

答案 0 :(得分:3)

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

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

的方法

<CreateIfNotExistsAsync>d__1.MoveNext:

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

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被标记为“部分覆盖”,与完全覆盖的内容基本相同