2011-11-08 13 views
2

は、私はこれは私のテストで呼び出されたスリープ非同期CTP v3では、MSテストとのThread.sleep

public Task LongRunning() { 
    return Task.Factory.StartNew(
     () => { 
      Trace.TraceInformation("Start Sleep"); 

      Thread.Sleep(10000); 

      Trace.TraceInformation("End Sleep"); 
     }); 
} 

を使用して、長い実行中のタスクの方法を持っており、それが正常に

[TestMethod] 
public void SimpleContinueWith() { 
    Trace.TraceInformation("Start"); 

    LongRunning() 
     .ContinueWith(
      t => Trace.TraceInformation("End") 
     ).Wait(); 
} 

> QTAgent32.exe Information: 0 : Start 
> QTAgent32.exe Information: 0 : Start Sleep 
> QTAgent32.exe Information: 0 : End Sleep 
> QTAgent32.exe Information: 0 : End 

しかし、使用して動作します非同期/テストがまっすぐ落ちるのを待つ

[TestMethod] 
public async void SimpleAwait() { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
} 

> QTAgent32.exe Information: 0 : Start 
> QTAgent32.exe Information: 0 : Start Sleep 

それはなぜですか?

答えて

4

MSTestは(現在)非同期テストを処理できません。 Microsoftが最終リリースにこれを追加するかどうかはわかりません。 更新:VS11 Betaは非同期ユニットテストのサポートを追加しました。下記参照。

非同期コンテキストを自分で提供することで、非同期メソッドをテストできます。非同期CTP(Microsoft Visual Studioの非同期CTP \ Samples \(C#テスト)ユニットTesting \ AsyncTestUtilities)に含まれているもの、またはAsyncContextという名前のものを使用できます。

[TestMethod] 
public void SimpleAwait() { 
    AsyncContext.Run(async() => 
    { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
    }); 
} 

アップデート、2012年2月5日:AsyncContextを使用して

は、あなたのテストは次のように記述することができ別のオプションは、新しいAsyncUnitTests libraryです。 NuGetパッケージは、あなたのTestClassからAsyncTestClassを変更することをインストールし、あなたの非同期ユニットテストがはるかに自然に書くことができます。

[TestMethod] 
public async void SimpleAwait() { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
} 

アップデート、2012-06-06:あなたはVS2012ベータ版にアップデートする場合は、定義することができます非同期ユニットテスト。彼らはただTaskを返すことがあります:私は持っているので、

[TestMethod] 
public async Task SimpleAwait() { 
    Trace.TraceInformation("Start"); 

    await LongRunning(); 

    Trace.TraceInformation("End"); 
} 
+0

スーパー、おかげで、nugetパッケージをインストールしhttp://nuget.org/List/Packages/Nito.AsyncEx –

+0

はところで、私がテストを書いていた理由でしたParallel.ForEachを呼び出す非同期メソッドと再帰 - async/awaitでは動作しませんが、上のテストと同じように動作します。すなわち、呼び出され、戻ってくることはありません。 AsyncContextがこれを修正しました - ありがとう –

関連する問題