2017-03-07 2 views
0

私は以下の機能を持っており、UnitTestを書く方法を知る必要があります。 (HandleError関数)グローバルエラーハンドラのユニットテストの方法は?

public partial class App : Application 
{ 
    public App() 
    { 
     this.Startup += App_Startup; 
     Dispatcher.UnhandledException += HandleError; 
    } 
    private void HandleError(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) 
    { 
     string exception = e.Exception.Message; 
     MessageBox.Show(exception + "\"", "Error", MessageBoxButton.OK, MessageBoxImage.Error); 
     e.Handled = true; 
    } 
} 

私はUnitTestにはかなり新しいので、あまり知らないかもしれません。

+0

その方法は、しっかりとUIの実装の懸念に結合されている:これは、マイクロソフトの偽物にイントロがある

[TestMethod] public void App_Handles_Exceptions_WithFakes() { using (ShimsContext.Create()) { string usedMessage = null; string usedError = null; System.Windows.Fakes.ShimMessageBox.ShowStringStringMessageBoxButtonMessageBoxImage = (s, s1, arg3, arg4) => { usedMessage = s; usedError = s1; return MessageBoxResult.OK; }; var app = new App(); var dapp = (DispatcherObject)app; var mi = typeof(Dispatcher).GetMethod("CatchException", BindingFlags.Instance | BindingFlags.NonPublic); var handled = (bool)mi.Invoke(dapp.Dispatcher, new object[] { new Exception("a") }); Assert.IsTrue(handled); Assert.AreEqual("a\"", usedMessage); Assert.AreEqual("Error", usedError); } } 

これは孤立してテストするのを困難にします。モックを置換するためのUIの問題を抽象化して、コードをより柔軟にテストして分離してください。 – Nkosi

+0

そのコードはどのプラットフォームで実行されていますか。 winform? wpf?.....? – Nkosi

+0

使用プラットフォームはwpf –

答えて

0

だから、良いニュースがあり、悪いニュースがあります。 良いニュース - はい、無料のVisual Studioでもユニットテストができます。 悪いニュース - スタティックMessageBox.Showを使用しているため、ユニットテストで実際に実際のボックスが表示されます。

ユニットテストコード:

[TestMethod] 
    public void App_Handles_Exceptions() 
    { 
     var app = new App(); 
     var dapp = (DispatcherObject)app; 
     var mi = typeof(Dispatcher).GetMethod("CatchException", BindingFlags.Instance | BindingFlags.NonPublic); 
     var handled = (bool)mi.Invoke(dapp.Dispatcher, new object[] { new Exception("a") }); 

     Assert.IsTrue(handled); 
    } 

あなたは(これは必須ですでも2017と、悲しそうに)のVisual Studioのエンタープライズ版を持って起こるならば今、あなたは、Microsoftの偽物機能を使用することができますし、テストがあります完全に副作用なしで単離した:https://msdn.microsoft.com/en-us/library/hh549175.aspx

関連する問題