.net 如何测试 WPF 用户界面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/58340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:48:47  来源:igfitidea点击:

How to test a WPF user interface?

.netwpftesting

提问by Matt David

Using win forms with an MVC/MVParchitecture, I would normally use a class to wrap a view to test the UI while using mocks for the model and controller/presenter. The wrapper class would make most everything in the UI an observable property for the test runner through properties and events.

使用具有MVC/ MVP架构的win 表单,我通常会使用一个类来包装视图以测试 UI,同时使用模型和控制器/演示者的模拟。包装器类将通过属性和事件使 UI 中的大部分内容成为测试运行器的可观察属性。

Would this be a viable approach to testing a WPF app? Is there a better way? Are there any gotchas to watch out for?

这是测试 WPF 应用程序的可行方法吗?有没有更好的办法?有什么需要注意的问题吗?

回答by Kjetil Klaussen

As for the testing itself, you're probably best off using the UI Automationframework. Or if you want a more fluent and wpf/winforms/win32/swt-independent way of using the framework, you could download Whitefrom Codeplex (provided that you're in a position to use open source code in your environment).

至于测试本身,您可能最好使用UI 自动化框架。或者,如果您想要更流畅且独立于 wpf/winforms/win32/swt 的框架使用方式,您可以从 Codeplex下载White(前提是您能够在您的环境中使用开源代码)。

For the gotchas; If you're trying to test your views, you will probably run in to some threading issues. For instance, if you're running NUnit the default testrunner will run in MTA (Multi-Threaded Appartment), while as WPF needs to run as STA (Single-threaded Appartment). Mike Twohas a real easy getting-started on unit testing WPF, but without considering the threading issue. Josh Smith has some thoughts on the threading issue in this post, and he also points to this articleby Chris Hedgate. Chris uses a modified version of Peter Provost's CrossThreadTestRunnerto wrap the MTA/STA issues in a bit more friendly way.

对于问题;如果您正在尝试测试您的视图,您可能会遇到一些线程问题。例如,如果您正在运行 NUnit,则默认测试运行程序将在 MTA(多线程应用程序)中运行,而 WPF 需要作为 STA(单线程应用程序)运行。Mike Two在单元测试 WPF 上有一个非常简单的入门,但没有考虑线程问题。Josh Smith 在这篇文章中对线程问题有一些想法,他还指出了 Chris Hedgate 的这篇文章。Chris 使用 Peter Provost 的CrossThreadTestRunner的修改版本以更友好的方式包装 MTA/STA 问题。

回答by aku

@Matt David,

@马特大卫,

Please read documentation and take a look at the code samples for Microsoft CompositeWPF(aka Prism). It's a project created specifically to teach how to deal with MVP/MVC architecture in test-driven manner. Their sample application contains unit tests for presenters\controllers and very cool acceptance tests for UI (they use White frameworkto simulate user actions)

请阅读文档并查看 Microsoft CompositeWPF(又名 Prism)的代码示例。这是一个专门为教授如何以测试驱动的方式处理 MVP/MVC 架构而创建的项目。他们的示例应用程序包含针对演示者\控制器的单元测试和非常酷的 UI 验收测试(他们使用White 框架来模拟用户操作)

回答by Gishu

Manually.I'm not a big fan of automated UI testingif that is what you're getting at. I'm not sure about the WPF guidances (need to read thru aku's links).. because they are still solidifying so to speak... WPF has not stabilized from the point of 'what is the right way'. Unless you're using one of these evolving frameworks.. I'd be conservative w.r.t. effort

手动。如果这就是你所得到的,我不是自动化UI 测试的忠实粉丝。我不确定 WPF 指南(需要通过 aku 的链接阅读)..因为它们仍在巩固可以这么说...... WPF 还没有从“什么是正确的方法”的角度稳定下来。除非你使用这些不断发展的框架之一..我会保守努力

  • Test (Automated preferably TDDed) the logic/presenters/controllers ruthlessly. I'm not advocating sloppiness or lethargy.
  • Keep the UI skin thin and get some nasty testersto go have a (manual) crack at it with exploratory testing - nothing is as good as a 'tester from Hell' when it comes to UIs. The effort : gain ratio from automating this kind of testing is huge, doesn't catch everything and doesn't make sense... except to pacify the higher ups 'Look Mgr! No hands! self-testing UIs!'
  • 无情地测试(自动化最好 TDDed)逻辑/演示者/控制器。我不是在提倡草率或嗜睡
  • 保持 UI 皮肤很薄,并让一些讨厌的测试人员通过探索性测试对其进行(手动)破解 - 在 UI 方面,没有什么比“来自地狱的测试人员”更好的了。努力:从自动化这种测试中获得的收益是巨大的,并没有抓住一切并且没有意义......除了安抚高层'看经理!没有手!自测用户界面!

PS: you may want to watch this (Mary Poppendieck's Google Talk on Lean).. especially the part about what to automate in testing

PS:你可能想看这个(Mary Poppendieck's Google Talk on Lean)..特别是关于在测试中自动化什么的部分

回答by Justas

2016 Update: Use the free TestStack.White framework to automate WPF UI testing

2016 更新:使用免费的 TestStack.White 框架来自动化 WPF UI 测试

  • Project White has been abandoned, but its successor TestStack.Whiteis available via a NuGet package.
  • TestStack.White has utility methods for starting WPF apps, findingwindow/user control elements, clicking buttons/elements, simulating mouse and keyboardevents, waiting, etc..
  • An example that will launch a WPF app, click a button, and check for result looks like the following:

    using TestStack.White;
    using TestStack.White.UIItems;
    using TestStack.White.Factory;
    
    [TestMethod]
    public void TestDoSomething()
    {
        //Opens the app
        var app = Application.Launch("MyApp.exe");
    
        //Finds the main window (this and above line should be in [TestInitialize])
        var window = app.GetWindow("My App Window Title", InitializeOption.NoCache);
    
        //Finds the button (see other Get...() methods for options)
        var btnMyButton = window.Get<Button>("btnMyButtonWPFname");
    
        //Simulate clicking
        btnMyButton.Click();
    
        //Gets the result text box 
        //Note: TextBox/Button is in TestStack.White.UIItems namespace
        var txtMyTextBox = window.Get<TextBox>("txtMyTextBox");
    
        //Check for the result
        Assert.IsTrue(txtMyTextBox.Text == "my expected result");
    
        //Close the main window and the app (preferably in [TestCleanup])
        app.Close();
    }
    
  • Project White 已被放弃,但其继任者TestStack.White可通过 NuGet 包获得。
  • TestStack.White 具有用于启动 WPF 应用程序查找窗口/用户控制元素单击按钮/元素、模拟鼠标和键盘事件、等待等的实用方法。
  • 将启动 WPF 应用程序、单击按钮并检查结果的示例如下所示:

    using TestStack.White;
    using TestStack.White.UIItems;
    using TestStack.White.Factory;
    
    [TestMethod]
    public void TestDoSomething()
    {
        //Opens the app
        var app = Application.Launch("MyApp.exe");
    
        //Finds the main window (this and above line should be in [TestInitialize])
        var window = app.GetWindow("My App Window Title", InitializeOption.NoCache);
    
        //Finds the button (see other Get...() methods for options)
        var btnMyButton = window.Get<Button>("btnMyButtonWPFname");
    
        //Simulate clicking
        btnMyButton.Click();
    
        //Gets the result text box 
        //Note: TextBox/Button is in TestStack.White.UIItems namespace
        var txtMyTextBox = window.Get<TextBox>("txtMyTextBox");
    
        //Check for the result
        Assert.IsTrue(txtMyTextBox.Text == "my expected result");
    
        //Close the main window and the app (preferably in [TestCleanup])
        app.Close();
    }
    

回答by HHenn

Because the Coded UI framework expires after Visual Studio version 2019 (Deprecated Coded UI), Microsoft recommends Appium with WinAppDriver for testing Windows applications (Desktop and UWP). You can use Appium (with WinAppDriver) or WinAppDriver directly to run the tests (WinAppDriver with or without Appium).

由于编码 UI 框架在 Visual Studio 2019 版(已弃用的编码 UI)之后过期,因此微软建议使用带有 WinAppDriver 的 Appium 来测试 Windows 应用程序(桌面和 UWP)。您可以直接使用 Appium(带有 WinAppDriver)或 WinAppDriver 来运行测试(带有或不带有 Appium 的 WinAppDriver)。

WinAppDriver directly

直接WinAppDriver

Here is a short description to work with the WinAppDriver directly:

以下是直接使用 WinAppDriver 的简短说明:

  • download and install WinAppDriver:

    WinAppDriver Release

  • enable Developer Mode in Windows settings
  • start the WinAppDriver:

    C:\Program Files (x86)\Windows Application Driver\WinAppDriver.exe

  • create a new Visual Studio 2019 Unit Test Project (.NET Framework)

  • add the NuGet-Package: Appium.WebDriver

  • add a new class DesktopSession:
  • 下载并安装 WinAppDriver:

    WinAppDriver 发布

  • 在 Windows 设置中启用开发者模式
  • 启动 WinAppDriver:

    C:\Program Files (x86)\Windows 应用程序驱动程序\WinAppDriver.exe

  • 创建一个新的 Visual Studio 2019 单元测试项目 (.NET Framework)

  • 添加 NuGet 包:Appium.WebDriver

  • 添加一个新类 DesktopSession:
    public class DesktopSession
    {
        protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
        private const string NotepadAppId = @"C:\Windows\System32\notepad.exe";

        protected static WindowsDriver<WindowsElement> session;
        protected static WindowsElement editBox;

        public static void Setup(TestContext context)
        {
            // Launch a new instance of Notepad application
            if (session == null)
            {
                // Create a new session to launch Notepad application
                var appCapabilities = new DesiredCapabilities();
                appCapabilities.SetCapability("app", NotepadAppId);
                appCapabilities.SetCapability("platformName", "Windows");
                appCapabilities.SetCapability("deviceName ", "WindowsPC");
                session = new WindowsDriver<WindowsElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
                Assert.IsNotNull(session);
                Assert.IsNotNull(session.SessionId);

                // Set implicit timeout to 1.5 seconds to make element search to retry every 500 ms for at most three times
                session.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1.5));

                // Keep track of the edit box to be used throughout the session
                editBox = session.FindElementByClassName("Edit");
                Assert.IsNotNull(editBox);
            }
        }

        public static void TearDown()
        {
            // Close the application and delete the session
            if (session != null)
            {
                session.Close();

                try
                {
                    // Dismiss Save dialog if it is blocking the exit
                    session.FindElementByName("Nicht speichern").Click();
                }
                catch { }

                session.Quit();
                session = null;
            }
        }

        [TestInitialize]
        public void TestInitialize()
        {
            // Select all text and delete to clear the edit box
            editBox.SendKeys(Keys.Control + "a" + Keys.Control);
            editBox.SendKeys(Keys.Delete);
            Assert.AreEqual(string.Empty, editBox.Text);
        }
    } 
  • Change the code from the UnitTest1 class
  • 更改 UnitTest1 类中的代码
        [TestClass]
        public class UnitTest1 : DesktopSession
        {
            [TestMethod]
            public void EditorEnterText()
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                editBox.SendKeys("abcdeABCDE 12345");
                Assert.AreEqual(@"abcdeABCDE 12345", editBox.Text);
            }

            [ClassInitialize]
            public static void ClassInitialize(TestContext context)
            {
                Setup(context);
            }

            [ClassCleanup]
            public static void ClassCleanup()
            {
                TearDown();
            }
        }
  • run your test
  • 运行你的测试

(the sample code is mainly copied from WinAppDriver .NotepadTest).

(示例代码主要复制自WinAppDriver .NotepadTest)。

Appium with WinAppDriver

带有 WinAppDriver 的 Appium

If you want to run your tests using Appium, then you must have installed the correct version of the WinAppDriver on your machine. The installer of Appium should also install the WinAppDriver with the correct version on your machine (please install Appium for all users). In my case, unfortunately, this did not work. So I take a look in the file:

如果你想使用 Appium 运行你的测试,那么你必须在你的机器上安装了正确版本的 WinAppDriver。Appium 的安装程序还应该在您的机器上安装正确版本的 WinAppDriver(请为所有用户安装 Appium)。不幸的是,就我而言,这不起作用。所以我看了一下文件:

C:\Program Files\Appium\resources\app\node_modules\appium\node_modules\appium-windows-driver\lib\installer.js

Here you will find the correct version and the download path:

在这里你会找到正确的版本和下载路径:

const WAD_VER = "1.1";
const WAD_DL = `https://github.com/Microsoft/WinAppDriver/releases/download/v${WAD_VER}/WindowsApplicationDriver.msi`;

If you have installed the correct WinAppDriver you can start Appium.

如果您安装了正确的 WinAppDriver,您就可以启动 Appium。

Important: you have to change the ApplicationDriverUrl

重要提示:您必须更改 ApplicationDriverUrl

protected const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723/wd/hub";

Tools:

工具:

WindowsAppDriver and UI REcorder releasesor Donwload the WinAppDriver repositoryand build the WinAppDriverUIRecorder.sln in the subdirectory tools\UIRecorder

WindowsAppDriver 和 UI REcorder 发布或下载WinAppDriver 存储库并在子目录 tools\UIRecorder 中构建 WinAppDriverUIRecorder.sln

Introducing WinAppDriver UI Recorder

介绍 WinAppDriver UI 记录器

  • inspect.exe: Windows SDK is required (look in C:\Program Files (x86)\Windows Kits\10\bin)
  • inspect.exe:需要 Windows SDK(在 C:\Program Files (x86)\Windows Kits\10\bin 中查找)

Other links: WinAppDriver FAQAppium

其他链接: WinAppDriver 常见问题Appium

回答by Ruben Bartelink

Definitely look at TestAutomationFX.com. One can invest (OK, I did) a lot of time trying to capture / record events with White. (At the start of my quest I ignored the post or two in other places referring to it).

一定要看看 TestAutomationFX.com。一个人可以投入(好吧,我做到了)大量时间尝试用怀特捕捉/记录事件。(在我的任务开始时,我忽略了其他地方提到的一两个帖子)。

I of course second the other points about the best type of testing not being UI testing.

我当然第二点关于最好的测试类型不是 UI 测试。

But if someone is going to do something automatable in the UI to get around shortcomings in other types of testing coverage, TAFX seems the quickest route there.

但是如果有人打算在 UI 中做一些可自动化的事情来解决其他类型测试覆盖范围的缺点,TAFX 似乎是那里最快的途径。

回答by Ruben Bartelink

Try Ranorex V2.0 for WPF automation. With RanoreXPath and Ranorex repository test automation code could be completely seperated from identification information. Ranorex also provides a capture/replay editor based on RanoreXPath objects.

尝试使用 Ranorex V2.0 实现 WPF 自动化。使用 RanoreXPath 和 Ranorex 存储库测试自动化代码可以与识别信息完全分离。Ranorex 还提供了一个基于 RanoreXPath 对象的捕获/重放编辑器。

回答by Gokul

I would recommend TestAutomationFX as well for simple automation of ui testing. TestAutomationFX lets you work with netAdvantage tools for wpf aswell , which doesnt work with white and QTP. TestAutomationFX has a easy to use interface , it integrates with visual studio and has a good recorder for recording user events.

我会推荐 TestAutomationFX 以及用于 ui 测试的简单自动化。TestAutomationFX 允许您使用 wpf 以及不适用于白色和 QTP 的 netAdvantage 工具。TestAutomationFX 具有易于使用的界面,它与visual studio 集成,并具有用于记录用户事件的良好记录器。