gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:08:08 25 4
gpt4 key购买 nike

我有以下方法:

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

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

Two blocks not covered

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

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

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

最佳答案

好吧 - 经过大量挖掘 - 罪魁祸首是 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操作码。

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

坏消息是,我没有解决方案。我的建议是:使用代码覆盖率作为指南,因为即使是 100% 的覆盖率也不意味着代码没有错误。话虽如此,你可以从逻辑上推导出throw标记为“部分覆盖”与完全覆盖基本相同

关于c# - 这种方法能达到100%的代码覆盖率吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40422362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com