1

単体テスト (Visual Studio 2012 単体テスト環境) でランタイム設定 ThrowUnobservedTaskExceptions を有効にするにはどうすればよいですか?

単体テスト プロジェクトに App.config ファイルを追加しようとしました。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <ThrowUnobservedTaskExceptions enabled="true"/>
  </runtime>
</configuration>

残念ながら、これは機能しません。タスクが未処理の例外をスローするため、次の単体テストは失敗するはずです。どうすればこれを達成できますか?

[TestMethod]
public void TestMethod()
{
    Task.Factory.StartNew(() =>
    {
        throw new InvalidOperationException("Test");
    });

    // Sleep is necessary so that the task can finish.
    Thread.Sleep(100);
    // GC.Collect is necessary so that the finalizer of the 
    // Task is called which throws the exception.
    GC.Collect();
}

上記の単体テストは、私が抱えている問題を再現するための単純化されたサンプルです。これらの未処理の例外は、外部ライブラリ内で呼び出される可能性があり、例外を自分で処理する方法はありません。

4

1 に答える 1

2

I'm not sure how to cause your test to fail, but the following code at least resulted in the exception information appearing in the test output:

[TestInitialize]
public void SetThrowUnobservedTaskExceptions()
{
    Type taskExceptionHolder = typeof(Task).Assembly
        .GetType("System.Threading.Tasks.TaskExceptionHolder", false);
    if (taskExceptionHolder != null)
    {
        var field = taskExceptionHolder.GetField("s_failFastOnUnobservedException",
            BindingFlags.Static | BindingFlags.NonPublic);
        field.SetValue(null, true);
    }
}

It looks like the native code for the finalizer thread checks an additional property which cannot be set through reflection, which actually causes the process to terminate. I'm not 100% sure on this though.

于 2014-12-08T17:43:58.940 に答える