【问题标题】:Testing UnityBootstrapper Implementation Fails Due to Application.Current being null由于 Application.Current 为空,测试 UnityBootstrapper 实现失败
【发布时间】:2016-12-26 15:21:14
【问题描述】:

由于 Application.Current 为空,测试 UnityBootstrapper 实现失败

我正在使用 TDD、Prism 和 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);
    }
}

当我运行应用程序时,一切都按预期工作;只有在运行测试时,我才会得到空异常。

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();
    }        
}

我想知道在执行测试期间如何避免这个问题。

【问题讨论】:

  • 做一个空检查,只有当它不为空时才尝试设置属性。

标签: wpf unit-testing mvvm tdd xunit


【解决方案1】:

做一个空检查,只有当它不为空时才尝试设置属性。

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

这样,当测试并且Application.Currentnull 时,测试将跳过尝试访问导致 NPE 的属性。

【讨论】:

  • 感谢您的建议。我愿意试试。我想知道是否有办法在不添加空检查的情况下解决这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多