Question

I need to test my library with Unit Testing.

Unfortunately the library takes as a parameter a System.Windows.Application instance. Normally in the real world WPF application this would be the public partial class App : Application entry App.xaml application class.

This is needed for the DispatcherUnhandledException event that the library uses to register a handler.

Is there a way to mock or to initialize the Application.Current, which is null in a WPF Unit Test library?

Thank you.

Was it helpful?

Solution

Wrap it with another class implementing an interface. When unit testing inject the mock implementation.

public interface IExceptionManager
{
    event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;
}

public class ExceptionManager : IExceptionManager
{
    Application _app;

    public ExceptionManager(Application app)
    {
        _app = app;
    }

    public event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException
    {
        add
        {
            _app.DispatcherUnhandledException += value;
        }

        remove
        {
            _app.DispatcherUnhandledException -= value;
        }
    }
}

public class MockExceptionManager: IExceptionManager
{
    public event DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;
}

OTHER TIPS

Hmm ... Usually this is what your App.xaml.cs looks like (I've added a property that you can access, but disregard it if you don't need it):

    public partial class App : Application
    {
        static App()
        {
            DispatcherHelper.Initialize();
            ExampleProp = "whatever floats your boat here";

        }

        /// <summary>
        /// You can access this from any class by using "App.ExampleProp".
        /// </summary>
        public static string ExampleProp{ get; set; }
    }
}

Now, you can access this from any place using the "App.MyExampleProp", but more to the point, since App extends Application, it also have App.Current, which is what you were after, letting you access the current application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top