Unit test WPF Bindings

后端 未结 5 571
萌比男神i
萌比男神i 2021-01-04 11:08

I am trying to unit test my WPF databindings using the test suit provided by Microsoft Team System. I would like to be able to test the bindings without showing the window

5条回答
  •  旧巷少年郎
    2021-01-04 11:29

    Combining advice I came across in a number of SO posts I wrote the following class which works very well to test WPF bindings.

    public static class WpfBindingTester
    {
        /// load a view in a hidden window and monitor it for binding errors
        /// a data-bound view to load and monitor for binding errors
        public static void AssertBindings(object view)
        {
            using (InternalTraceListener listener = new InternalTraceListener())
            {
                ManualResetEventSlim mre = new ManualResetEventSlim(false);
    
                Window window = new Window
                {
                    Width = 0,
                    Height = 0,
                    WindowStyle = WindowStyle.None,
                    ShowInTaskbar = false,
                    ShowActivated = false,
                    Content = view
                };
    
                window.Loaded += (_, __) => mre.Set();
                window.Show();
    
                mre.Wait();
    
                window.Close();
    
                Assert.That(listener.ErrorMessages, Is.Empty, listener.ErrorMessages);
            }
        }
    
        /// Is the test running in an interactive session. Use with Assume.That(WpfBindingTester.IsAvailable) to make sure tests only run where they're able to
        public static bool IsAvailable { get { return Environment.UserInteractive && Process.GetCurrentProcess().SessionId != 0; } }
    
    
        private class InternalTraceListener : TraceListener
        {
            private readonly StringBuilder _errors = new StringBuilder();
            private readonly SourceLevels _originalLevel;
            public string ErrorMessages { get { return _errors.ToString(); } }
    
            static InternalTraceListener() { PresentationTraceSources.Refresh(); }
    
            public InternalTraceListener()
            {
                _originalLevel = PresentationTraceSources.DataBindingSource.Switch.Level;
                PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
                PresentationTraceSources.DataBindingSource.Listeners.Add(this);
            }
    
            public override void Write(string message) {}
    
            public override void WriteLine(string message) { _errors.AppendLine(message); }
    
            protected override void Dispose(bool disposing)
            {
                PresentationTraceSources.DataBindingSource.Listeners.Remove(this);
                PresentationTraceSources.DataBindingSource.Switch.Level = _originalLevel;
                base.Dispose(disposing);
            }
        }
    }
    

提交回复
热议问题