【问题标题】:Trying to use Application.Current in TestCase, however Application cannot be imported from System.Windows尝试在 TestCase 中使用 Application.Current,但无法从 System.Windows 导入应用程序
【发布时间】:2018-08-11 02:23:50
【问题描述】:

我尝试对一个 Gui 应用程序代码进行单元测试,该代码使用 Application.Current.Dispatcher.Invoke() 并希望使用@informatorius 在类似线程Using the WPF Dispatcher in unit tests 中提供的解决方案。代码如下。

我的问题是Application 没有解决,即使我添加了using System.Windows。是否有一些特殊的机制来解决 Application 来自定义测试用例的类库? 我安装了MSTest.TestFrameworkMSTest.TestAdapter 软件包。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass] 
public class ApplicationInitializer
{
    [AssemblyInitialize]
    public static void AssemblyInitialize(TestContext context)
    {
        var waitForApplicationRun = new TaskCompletionSource<bool>();
        Task.Run(() =>
        {
            var application = new Application();
            application.Startup += (s, e) => { waitForApplicationRun.SetResult(true); };
            application.Run();
        });
        waitForApplicationRun.Task.Wait();
    }
    [AssemblyCleanup]
    public static void AssemblyCleanup()
    {
        Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
    }
}

[TestClass]
public class MyTestClass
{
    [TestMethod]
    public void MyTestMethod()
    {
        // implementation can access Application.Current.Dispatcher
    }
}

【问题讨论】:

    标签: c# unit-testing


    【解决方案1】:

    Answer 为我指明了正确的方向: using System.Windows 还不够,我还需要在项目中添加对PresentationFramework 的引用。不太了解这背后的汽车魔法。

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2020-06-21
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 2011-07-04
      • 1970-01-01
      • 2016-06-24
      相关资源
      最近更新 更多