GuOrg / Gu.Wpf.UiAutomation

MIT License
96 stars 17 forks source link

Add check that there are no trace messages. Not sure it works from out of process but chances are it does. #63

Open JohanLarsson opened 6 years ago

JohanLarsson commented 6 years ago
using System.Collections.Generic;
using System.Diagnostics;

public class WpfTraceListener : TraceListener
{
    private readonly List<string> messages = new List<string>();

    public WpfTraceListener()
    {
        Register(PresentationTraceSources.AnimationSource);
        Register(PresentationTraceSources.DataBindingSource);
        Register(PresentationTraceSources.DocumentsSource);
        Register(PresentationTraceSources.DependencyPropertySource);
        Register(PresentationTraceSources.FreezableSource);
        Register(PresentationTraceSources.HwndHostSource);
        Register(PresentationTraceSources.MarkupSource);
        Register(PresentationTraceSources.NameScopeSource);
        Register(PresentationTraceSources.ResourceDictionarySource);
        Register(PresentationTraceSources.RoutedEventSource);
        Register(PresentationTraceSources.ShellSource);

        void Register(TraceSource source)
        {
            source.Listeners.Add(this);
            source.Switch.Level = SourceLevels.Warning | SourceLevels.Error;
        }
    }

    public IReadOnlyList<string> Messages => this.messages;

    public override void Write(string message)
    {
    }

    public override void WriteLine(string message)
    {
        this.messages.Add(message);
    }
}
JohanLarsson commented 6 years ago

Idea for usage:

[Test]
public void ClickAllTabs()
{
    using (var listener = new ObservableTraceListener())
    {
        using (var app = Application.Launch("Gu.Wpf.FlipView.Demo.exe"))
        {
            var window = app.MainWindow;
            var tab = window.FindTabControl();
            foreach (var tabItem in tab.Items)
            {
                _ = tabItem.Select();
            }
        }

        Assert.IsEmpty(listener.Messages);
    }
}