我有以下方法:此方法可以达到100%的代码覆盖率吗?
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)表明,两个块不包括:
我想这有一些东西需要使用为await
一个catch块内生成的代码,所以我尝试改写这样的方法:
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;
}
}
在您的第一张图片中,哪些区块未被覆盖..? – Rob
我猜蓝色意味着覆盖;橙色意味着没有涵盖;紫色部分覆盖。所以我会说'抛出;'和'}'尽管'throw' **被覆盖,并且'}'甚至没有被覆盖的代码... –
'}'不是'可包含的',我猜它没有被突出显示,因为代码永远不会超出该范围(这很好 - 同样的事情发生在返回语句之后)。至于投掷,这与结构无关,这是因为异常是可以抑制的,任务没有被取消。所以,你需要编写一个新的测试(使用原始代码),导致一个不可压制的异常,或者取消任务 – Rob