6

簡単なデータのダウンロードをテストするためのテストメソッドを作成しようとしています。ダウンロードが HttpRequestException で失敗するテスト ケースを作成しました。非非同期バージョンをテストすると、テストはうまく機能し、合格しますが、asnyc バージョンをテストすると失敗します。

async/await メソッドの場合に Assert.ThrowsException を使用する際の秘訣は何ですか?

[TestMethod]
    public void FooAsync_Test()
    {
        Assert.ThrowsException<System.Net.Http.HttpRequestException>
(async () => await _dataFetcher.GetDataAsync());
    }
4

3 に答える 3

7

AFAICT、マイクロソフトはそれを含めるのを忘れただけです。それは確かにIMOにあるはずです(同意する場合は、UserVoice に投票してください)。

それまでの間、以下の方法を使用できます。それは私の AsyncEx ライブラリAsyncAssertのクラスからのものです。近い将来、NuGet ライブラリとしてリリースする予定ですが、今のところ、これをテスト クラスに入れることができます。AsyncAssert

public static async Task ThrowsAsync<TException>(Func<Task> action, bool allowDerivedTypes = true)
{
    try
    {
        await action();
        Assert.Fail("Delegate did not throw expected exception " + typeof(TException).Name + ".");
    }
    catch (Exception ex)
    {
        if (allowDerivedTypes && !(ex is TException))
            Assert.Fail("Delegate threw exception of type " + ex.GetType().Name + ", but " + typeof(TException).Name + " or a derived type was expected.");
        if (!allowDerivedTypes && ex.GetType() != typeof(TException))
            Assert.Fail("Delegate threw exception of type " + ex.GetType().Name + ", but " + typeof(TException).Name + " was expected.");
    }
}
于 2012-11-30T02:57:11.917 に答える