21

有没有人举例说明如何在 Windows 8 Metro 应用程序中对异步方法进行单元测试,以确保它抛出所需的异常?

给定一个具有异步方法的类

public static class AsyncMathsStatic
{
    private const int DELAY = 500;

    public static async Task<int> Divide(int A, int B)
    {
        await Task.Delay(DELAY);
        if (B == 0)
            throw new DivideByZeroException();
        else
            return A / B;
    }
}

我想使用新的 Async.ExpectsException 构造编写一个测试方法。我试过了 :-

[TestMethod]
public void DivideTest1()
{
    Assert.ThrowsException<DivideByZeroException>(async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
}

但是当然测试不会等待异步方法完成,因此会导致测试失败,即没有引发异常。

4

7 回答 7

21

您可以将async Task单元测试与常规一起使用ExpectedExceptionAttribute

[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public async Task DivideTest1()
{
  int Result = await AsyncMathsStatic.Divide(4, 0);
}

评论更新: ExpectedExceptionAttribute在 Win8 单元测试项目上已被替换Assert.ThrowsException,这是很好的无证 AFAICT。这是一个很好的设计方面的改变,但我不知道为什么它只支持 Win8。

好吧,假设没有async-compatible (由于缺少文档,Assert.ThrowsException我无法判断是否有) ,您可以自己构建一个:

public static class AssertEx
{
  public async Task ThrowsExceptionAsync<TException>(Func<Task> code)
  {
    try
    {
      await code();
    }
    catch (Exception ex)
    {
      if (ex.GetType() == typeof(TException))
        return;
      throw new AssertFailedException("Incorrect type; expected ... got ...", ex);
    }

    throw new AssertFailedException("Did not see expected exception ...");
  }
}

然后这样使用它:

[TestMethod]
public async Task DivideTest1()
{
  await AssertEx.ThrowsException<DivideByZeroException>(async () => { 
      int Result = await AsyncMathsStatic.Divide(4, 0);
  });
}

请注意,我在这里的示例只是对异常类型进行精确检查;您可能更喜欢允许后代类型。

2012-11-29 更新:打开了UserVoice 建议以将其添加到 Visual Studio。

于 2012-10-11T10:40:23.913 回答
4
[TestMethod]
public void DivideTest1()
{
    Func<Task> action = async () => { int Result = await AsyncMathsStatic.Divide(4, 0); });
    action.ShouldThrow<DivideByZeroException>();
}

使用.ShouldThrow()FluentAssertions nuget 包对我有用

于 2017-06-08T12:07:39.520 回答
3

通过添加ThrowsExceptionAsyncmethod,现在可以在本机覆盖,而无需 MSTest 中的第三方或扩展方法:

await Assert.ThrowsExceptionAsync<Exception>(() => { Fail(); });
于 2020-08-21T09:54:31.877 回答
1

几天前我遇到了一个类似的问题,最终创建了类似于斯蒂芬上面的答案的东西。它可以作为Gist使用。希望它对您有所帮助 - github gist 有完整的代码和示例用法。

/// <summary>
/// Async Asserts use with Microsoft.VisualStudio.TestPlatform.UnitTestFramework
/// </summary>
public static class AsyncAsserts
{
    /// <summary>
    /// Verifies that an exception of type <typeparamref name="T"/> is thrown when async<paramref name="func"/> is executed.
    /// The assertion fails if no exception is thrown
    /// </summary>
    /// <typeparam name="T">The generic exception which is expected to be thrown</typeparam>
    /// <param name="func">The async Func which is expected to throw an exception</param>
    /// <returns>The task object representing the asynchronous operation.</returns>
    public static async Task<T> ThrowsException<T>(Func<Task> func) where T : Exception
    {
        return await ThrowsException<T>(func, null);
    }

    /// <summary>
    /// Verifies that an exception of type <typeparamref name="T"/> is thrown when async<paramref name="func"/> is executed.
    /// The assertion fails if no exception is thrown
    /// </summary>
    /// <typeparam name="T">The generic exception which is expected to be thrown</typeparam>
    /// <param name="func">The async Func which is expected to throw an exception</param>
    /// <param name="message">A message to display if the assertion fails. This message can be seen in the unit test results.</param>
    /// <returns>The task object representing the asynchronous operation.</returns>
    public static async Task<T> ThrowsException<T>(Func<Task> func, string message) where T : Exception
    {
        if (func == null)
        {
            throw new ArgumentNullException("func");
        }

        string failureMessage;
        try
        {
            await func();
        }
        catch (Exception exception)
        {
            if (!typeof(T).Equals(exception.GetType()))
            {
                // "Threw exception {2}, but exception {1} was expected. {0}\nException Message: {3}\nStack Trace: {4}"
                failureMessage = string.Format(
                    CultureInfo.CurrentCulture,
                    FrameworkMessages.WrongExceptionThrown,
                    message ?? string.Empty,
                    typeof(T),
                    exception.GetType().Name,
                    exception.Message,
                    exception.StackTrace);

                Fail(failureMessage);
            }
            else
            {
                return (T)exception;
            }
        }

        // "No exception thrown. {1} exception was expected. {0}"
        failureMessage = string.Format(
                    CultureInfo.CurrentCulture,
                    FrameworkMessages.NoExceptionThrown,
                    message ?? string.Empty,
                    typeof(T));

        Fail(failureMessage);
        return default(T);
    }

    private static void Fail(string message, [CallerMemberName] string assertionName = null)
    {
        string failureMessage = string.Format(
            CultureInfo.CurrentCulture,
            FrameworkMessages.AssertionFailed,
            assertionName,
            message);

        throw new AssertFailedException(failureMessage);
    }
}
于 2012-10-16T06:40:25.283 回答
1

这是一个老问题,但我现在偶然发现了这个问题,并决定对这个问题给出更新的答案。

Xuint 现在支持使用Assert.ThrowsAsync方法进行异步异常测试。

于 2021-06-21T16:36:18.080 回答
0

Visual Studio 2012 Update 2 中添加了对在ThrowsException方法中使用异步 lambda 的支持,但仅适用于 Windows Store 测试项目。

一个问题是您需要使用Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AppContainer.Assert类来调用ThrowsException.

因此,要使用新的 ThrowsException 方法,您可以执行以下操作:

using AsyncAssert = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.AppContainer.Assert;

[TestMethod]
public void DivideTest1()
{
    AsyncAssert.ThrowsException<DivideByZeroException>(async () => { 
        int Result = await AsyncMathsStatic.Divide(4, 0); });
}
于 2014-06-08T23:24:01.603 回答
0

这对我有用

    public async Task TestMachineAuthBadJson() {
        // Arrange

        // act
        DocsException ex = await Assert.ThrowsExceptionAsync<DocsException>(() => MachineAuth.GetToken());
        //assert
        StringAssert.Contains(ex.Message, "DOCS-API error: ");

        }
于 2021-03-09T18:03:24.043 回答