如何在需要WPF应用程序时进行单元测试?

Geo*_*kos 1 c# wpf xaml unit-testing applicationcontext

我需要使用单元测试来测试我的库.

不幸的是,该库将System.Windows.Application实例作为参数.通常在现实世界的WPF应用程序中,这将是public partial class App : Application入口App.xaml应用程序类.

这是DispatcherUnhandledException库用于注册处理程序的事件所必需的.

有没有办法模拟或初始化Application.Current,在WPF单元测试库中为null?

谢谢.

Max*_*kiy 6

用另一个实现接口的类包装它.当单元测试注入模拟实现时.

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;
}
Run Code Online (Sandbox Code Playgroud)