WPF、MVVM、NUnit 和线程……我做错了吗

WPF, MVVM, NUnit, and Threads.. am I doing it wrong

所以..我有 WPF 和 MVVM 模式。 ViewModel 中的一个线程正在 运行 执行更新可观察集合的任务,因此当它添加到集合中时,我会这样做:

Application.Current.Dispatcher.Invoke((Action) (() => 
{
    _files.Add(toAdd);
}));

有效...问题是当我进行 NUnit 测试时,据我所知没有 UI 线程,所以我必须先 运行 将文件添加到没有调用的集合:

if (Application.Current == null) {
   _files.Add(toAdd);
}));

所以只是为了澄清一下它的样子

if (Application.Current == null) {
   _files.Add(toAdd);
   return;
}));

Application.Current.Dispatcher.Invoke((Action) (() => 
{
    _files.Add(toAdd);
}));

这感觉不对,因为我在视图模型中添加了两行逻辑,其中一行有 UI,另一行纯粹用于测试。

有人知道我的方法哪里出了问题,或者这是否真的可以接受?

谢谢

我的 ViewModel 在其构造函数中需要一个 IUIThreadHelper。

    public MyViewModel(IUIThreadHelper uiThreadHelper)
    {
        if (uiThreadHelper == null)
            throw new ArgumentNullException(nameof(uiThreadHelper));
        this.uiThreadHelper = uiThreadHelper;
    }

IUIThreadHelper 看起来像:

public interface IUIThreadHelper
{
    void InvokeAction(Action action);
}

正常情况下运行我给它一个使用应用程序调度程序的 UIThreadHelper。

在测试中我给了它一个简单的假:

        IUIThreadHelper uiThreadHelper = new Fakes.StubIUIThreadHelper()
        {
            InvokeActionAction = (a) => a(),
        };

所以我可以简单地将它用作:

this.uiThreadHelper.InvokeAction(() => header.Children.Add(newChild));