CollectionChangedEventManagerTests.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.Text;
  5. using Avalonia.Collections;
  6. using Avalonia.Controls.Utils;
  7. using Xunit;
  8. using CollectionChangedEventManager = Avalonia.Controls.Utils.CollectionChangedEventManager;
  9. namespace Avalonia.Controls.UnitTests.Utils
  10. {
  11. public class CollectionChangedEventManagerTests
  12. {
  13. [Fact]
  14. public void AddListener_Listens_To_Events()
  15. {
  16. var source = new AvaloniaList<string>();
  17. var listener = new Listener();
  18. CollectionChangedEventManager.Instance.AddListener(source, listener);
  19. Assert.Empty(listener.Received);
  20. source.Add("foo");
  21. Assert.Equal(1, listener.Received.Count);
  22. }
  23. [Fact]
  24. public void RemoveListener_Stops_Listening_To_Events()
  25. {
  26. var source = new AvaloniaList<string>();
  27. var listener = new Listener();
  28. CollectionChangedEventManager.Instance.AddListener(source, listener);
  29. CollectionChangedEventManager.Instance.RemoveListener(source, listener);
  30. source.Add("foo");
  31. Assert.Empty(listener.Received);
  32. }
  33. [Fact]
  34. public void Receives_Events_From_Wrapped_Collection()
  35. {
  36. var source = new WrappingCollection();
  37. var listener = new Listener();
  38. CollectionChangedEventManager.Instance.AddListener(source, listener);
  39. Assert.Empty(listener.Received);
  40. source.Add("foo");
  41. Assert.Equal(1, listener.Received.Count);
  42. }
  43. private class Listener : ICollectionChangedListener
  44. {
  45. public List<NotifyCollectionChangedEventArgs> Received { get; } = new List<NotifyCollectionChangedEventArgs>();
  46. public void Changed(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
  47. {
  48. Received.Add(e);
  49. }
  50. public void PostChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
  51. {
  52. }
  53. public void PreChanged(INotifyCollectionChanged sender, NotifyCollectionChangedEventArgs e)
  54. {
  55. }
  56. }
  57. private class WrappingCollection : INotifyCollectionChanged
  58. {
  59. private AvaloniaList<string> _inner = new AvaloniaList<string>();
  60. public void Add(string s) => _inner.Add(s);
  61. public event NotifyCollectionChangedEventHandler CollectionChanged
  62. {
  63. add => _inner.CollectionChanged += value;
  64. remove => _inner.CollectionChanged -= value;
  65. }
  66. }
  67. }
  68. }