From 4330451d2c53b561a87cf8fa0aef71792ee65efb Mon Sep 17 00:00:00 2001 From: Steven Kirk Date: Fri, 28 Aug 2020 15:43:04 +0200 Subject: [PATCH] Added tests for CollectionChangedEventManager. Including a failing test: `Receives_Events_From_Wrapped_Collection`. --- .../CollectionChangedEventManagerTests.cs | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 tests/Avalonia.Controls.UnitTests/Utils/CollectionChangedEventManagerTests.cs diff --git a/tests/Avalonia.Controls.UnitTests/Utils/CollectionChangedEventManagerTests.cs b/tests/Avalonia.Controls.UnitTests/Utils/CollectionChangedEventManagerTests.cs new file mode 100644 index 0000000000..8bbb5e456f --- /dev/null +++ b/tests/Avalonia.Controls.UnitTests/Utils/CollectionChangedEventManagerTests.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Text; +using Avalonia.Collections; +using Avalonia.Controls.Utils; +using Xunit; +using CollectionChangedEventManager = Avalonia.Controls.Utils.CollectionChangedEventManager; + +namespace Avalonia.Controls.UnitTests.Utils +{ + public class CollectionChangedEventManagerTests + { + [Fact] + public void AddListener_Listens_To_Events() + { + var source = new AvaloniaList(); + var listener = new Listener(); + + CollectionChangedEventManager.Instance.AddListener(source, listener); + + Assert.Empty(listener.Received); + + source.Add("foo"); + + Assert.Equal(1, listener.Received.Count); + } + + [Fact] + public void RemoveListener_Stops_Listening_To_Events() + { + var source = new AvaloniaList(); + var listener = new Listener(); + + CollectionChangedEventManager.Instance.AddListener(source, listener); + CollectionChangedEventManager.Instance.RemoveListener(source, listener); + + source.Add("foo"); + + Assert.Empty(listener.Received); + } + + [Fact] + public void Receives_Events_From_Wrapped_Collection() + { + var source = new WrappingCollection(); + var listener = new Listener(); + + CollectionChangedEventManager.Instance.AddListener(source, listener); + + Assert.Empty(listener.Received); + + source.Add("foo"); + + Assert.Equal(1, listener.Received.Count); + } + + private class Listener : ICollectionChangedListener + { + public List Received { get; } = new List(); + + public void Changed(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e) + { + Received.Add(e); + } + + public void PostChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e) + { + } + + public void PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e) + { + } + } + + private class WrappingCollection : INotifyCollectionChanged + { + private AvaloniaList _inner = new AvaloniaList(); + + public void Add(string s) => _inner.Add(s); + + public event NotifyCollectionChangedEventHandler CollectionChanged + { + add => _inner.CollectionChanged += value; + remove => _inner.CollectionChanged -= value; + } + } + } +}