2016-12-26 32 views
0

測試UnityBootstrapper執行失敗,因爲Application.Current被空測試UnityBootstrapper執行失敗,因爲Application.Current被空

我正在開發使用TDD,棱鏡和MVVM模式的WPF應用程序。在應用程序啓動後,當我編寫測試以驗證Bootstrapper容器不爲空時,測試失敗,因爲InitializeShell方法中的Application.Current爲空。

public class BootstrapperTests 
{ 
    [Fact] 
    public void BootstrapperServiceLocator() 
    { 
     // Arrange 
     var sut = new Bootstrapper(); 
     // Act 
     sut.Run(); 
     // Assert 
     Assert.NotNull(sut.Container); 
    } 
} 

Application.Current is null

當我運行應用程序一切正常;只有在運行測試時,我會得到空例外。

public class Bootstrapper : UnityBootstrapper 
{ 
    protected override DependencyObject CreateShell() 
    { 
     return ServiceLocator.Current.GetInstance<Shell>(); 
    } 

    protected override void InitializeShell() 
    { 
     base.InitializeShell(); 

     Application.Current.MainWindow = (Window) Shell; 
     Application.Current.MainWindow.Show(); 
    }   
} 

我想知道我在執行測試期間如何避免這個問題。

+0

做一個空檢查,並只嘗試設置屬性,如果它不爲null。 – Nkosi

回答

0

做一個空檢查,並只嘗試設置屬性,如果它不爲null。

protected override void InitializeShell() { 
    base.InitializeShell(); 
    if(Application.Current != null) { 
     Application.Current.MainWindow = (Window) Shell; 
     Application.Current.MainWindow.Show(); 
    } 
} 

這樣,測試時和Application.Currentnull,測試將跳過嘗試訪問導致NPE財產。

+0

感謝您的建議。我願意嘗試。我想知道是否有辦法解決這個問題,而不添加空檢查。 – oligodendrocito

相關問題