WeakEventHandlerManagerTests.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Avalonia.Utilities;
  7. using Xunit;
  8. namespace Avalonia.Base.UnitTests
  9. {
  10. public class WeakEventHandlerManagerTests
  11. {
  12. class EventSource
  13. {
  14. public event EventHandler<EventArgs> Event;
  15. public void Fire()
  16. {
  17. Event?.Invoke(this, new EventArgs());
  18. }
  19. }
  20. class Subscriber
  21. {
  22. private readonly Action _onEvent;
  23. public Subscriber(Action onEvent)
  24. {
  25. _onEvent = onEvent;
  26. }
  27. public void OnEvent(object sender, EventArgs ev)
  28. {
  29. _onEvent?.Invoke();
  30. }
  31. }
  32. [Fact]
  33. public void EventShouldBePassedToSubscriber()
  34. {
  35. bool handled = false;
  36. var subscriber = new Subscriber(() => handled = true);
  37. var source = new EventSource();
  38. WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, "Event",
  39. subscriber.OnEvent);
  40. source.Fire();
  41. Assert.True(handled);
  42. }
  43. [Fact]
  44. public void EventShouldNotBeRaisedAfterUnsubscribe()
  45. {
  46. bool handled = false;
  47. var subscriber = new Subscriber(() => handled = true);
  48. var source = new EventSource();
  49. WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, "Event",
  50. subscriber.OnEvent);
  51. WeakEventHandlerManager.Unsubscribe<EventArgs, Subscriber>(source, "Event",
  52. subscriber.OnEvent);
  53. source.Fire();
  54. Assert.False(handled);
  55. }
  56. [Fact]
  57. public void EventHandlerShouldNotBeKeptAlive()
  58. {
  59. bool handled = false;
  60. var source = new EventSource();
  61. AddCollectableSubscriber(source, "Event", () => handled = true);
  62. for (int c = 0; c < 10; c++)
  63. {
  64. GC.Collect();
  65. GC.Collect(3, GCCollectionMode.Forced, true);
  66. }
  67. source.Fire();
  68. Assert.False(handled);
  69. }
  70. private static void AddCollectableSubscriber(EventSource source, string name, Action func)
  71. {
  72. WeakEventHandlerManager.Subscribe<EventSource, EventArgs, Subscriber>(source, name, new Subscriber(func).OnEvent);
  73. }
  74. }
  75. }