Testing UnityBootstrapper Implementation Fails Due to Application.Current being null

76 Views Asked by At

Testing UnityBootstrapper implementation fails due to Application.Current being null

I am developing a WPF application using TDD, Prism, and the MVVM pattern. When I write a test to verify that the Bootstrapper container is not null after the Application starts the test fails because Application.Current is null in the InitializeShell method.

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

Application.Current is null

When I run the application everything works as expected; only when running the test, I get the null exception.

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

I would like to know how I could avoid this issue during the execution of the tests.

1

There are 1 best solutions below

1
On

Do a null check and only attempt to set the property if it is not null.

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

That way when testing and Application.Current is null, the test will step over trying to access the property that results in NPE.