nunit测试中的模态对话框将永远阻止测试运行器

时间:2019-03-27 14:50:11

标签: c# winforms nunit nunit-3.0

我想对UI类进行单元测试(实际上没有显示)。我通过调用构造函数,然后在其上调用各种方法来完成此操作(就像普通的类一样)。实际上,UI实际上根本不会被Windows显示。但是,某些UI在某些情况下会引发模式对话框,我想将其视为错误情况并通过测试。

我尝试了Timeout属性,但是它不起作用(Test1),它仅显示对话框并挂起测试。我有一个可以执行的实现(Test2),但是有点难看。

是否有一种更清洁的方式将模态窗口视为错误条件? /即使显示模式对话框也要强制超时。

我正在使用Visual Studio测试运行程序和nunit版本3

class Test
{
    //does not work
    [Test, Timeout(5000)]
    public void Test1()
    {
        //blocks test and timeout is not respected
        MessageBox.Show("It went wrong");
    }

    //works but is ugly
    [Test]
    public void Test2()
    {
        Task runUIStuff = new Task(()=>
        {
            MessageBox.Show("It went wrong"); 

        });
        runUIStuff.Start();

        Task.WaitAny(Task.Delay(5000), runUIStuff);

        if(!runUIStuff.IsCompleted)
        {
            Process.GetCurrentProcess().CloseMainWindow();
            Assert.Fail("Test did not complete after timeout");
        }
    }
}

更新

感谢您提供指向编码UI测试的指针。这看起来是一个很好的潜在解决方案。

因为在此期间我确实做了一些工作,所以我认为我会对其进行更新。该解决方案涉及在具有自定义超时/关闭实现的STA线程中运行测试。它是一个NUnitAttribute,因此可以像[Test]一样使用。这是很hacky的,并且(大概是)特定于Windows的,但是它似乎确实可以在我的环境中正常工作(我实际上根本不希望显示UI)。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Commands;

namespace CatalogueLibraryTests.UserInterfaceTests
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    class UITimeoutAttribute : NUnitAttribute, IWrapTestMethod
    {
        private readonly int _timeout;

        /// <summary>
        /// Allows <paramref name="timeout"/> for the test to complete before calling <see cref="Process.CloseMainWindow"/> and failing the test
        /// </summary>
        /// <param name="timeout">timeout in milliseconds</param>
        public UITimeoutAttribute(int timeout)
        {
            this._timeout = timeout;
        }

        /// <inheritdoc/>
        public TestCommand Wrap(TestCommand command)
        {
            return new TimeoutCommand(command, this._timeout);
        }

        private class TimeoutCommand : DelegatingTestCommand
        {
            private int _timeout;

            public TimeoutCommand(TestCommand innerCommand, int timeout): base(innerCommand)
            {
                _timeout = timeout;
            }

            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, IntPtr lParam);

            [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
            static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

            [DllImport("user32.dll")]
            static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);

            private string YesNoDialog = "#32770";

            private const UInt32 WM_CLOSE = 0x0010;
            private const UInt32 WM_COMMAND = 0x0111;
            private int IDNO = 7;


            public override TestResult Execute(TestExecutionContext context)
            {
                TestResult result = null;
                Exception threadException = null;

                Thread thread = new Thread(() =>
                {
                    try
                    {
                        result = innerCommand.Execute(context);
                    }
                    catch (Exception ex)
                    {
                        threadException = ex;
                    }
                });
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();

                try
                {
                    while (thread.IsAlive && (_timeout > 0  || Debugger.IsAttached))
                    {
                        Task.Delay(100).Wait();
                        _timeout -= 100;
                    }

                    int closeAttempts = 10;

                    if (_timeout <= 0)
                    {
                        //Sends WM_Close which closes any form except a YES/NO dialog box because yay
                        Process.GetCurrentProcess().CloseMainWindow();

                        //if it still has a window handle then presumably needs further treatment
                        IntPtr handle;

                        while((handle = Process.GetCurrentProcess().MainWindowHandle) != IntPtr.Zero)
                        {
                            if(closeAttempts-- <=0)
                                throw new Exception("Failed to close all windows even after multiple attempts");

                            StringBuilder sbClass = new StringBuilder(100);

                            GetClassName(handle, sbClass, 100);

                            //Is it a yes/no dialog
                            if (sbClass.ToString() == YesNoDialog && GetDlgItem(handle, IDNO) != IntPtr.Zero)
                                //with a no button
                                SendMessage(handle, WM_COMMAND, IDNO, IntPtr.Zero); //click NO!
                            else
                                SendMessage(handle, WM_CLOSE, 0, IntPtr.Zero); //Send Close
                        }

                        throw new Exception("UI test did not complete after timeout");
                    }


                    if (threadException != null)
                        throw threadException;

                    if(result == null)
                        throw new Exception("UI test did not produce a result");

                    return result;
                }
                catch (AggregateException ae)
                {
                    throw ae.InnerException;
                }
            }
        }
    }
}

用法

[Test, UITimeout(500)]
public void TestMessageBox()
{
    MessageBox.Show("hey");
}
[Test, UITimeout(500)]
public void TestMessageBoxYesNo()
{
    MessageBox.Show("hey","there",MessageBoxButtons.YesNo);
}

1 个答案:

答案 0 :(得分:1)

NUnit确实不适合测试UI。假定您在c#中使用Winforms进行标记,则应为此切换到CodedUI测试。 还可以尝试将代码从表单类中取出并绑定到视图模型。视图和视图模型将是可测试的,并且您的代码将更加简洁。