CollectionChangedEventManagerTests.cs 2.7 KB

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