WeakSubscriptionManagerTests.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 WeakSubscriptionManagerTests
  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 : IWeakSubscriber<EventArgs>
  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 EventShoudBePassedToSubscriber()
  34. {
  35. bool handled = false;
  36. var subscriber = new Subscriber(() => handled = true);
  37. var source = new EventSource();
  38. WeakSubscriptionManager.Subscribe(source, "Event", subscriber);
  39. source.Fire();
  40. Assert.True(handled);
  41. }
  42. [Fact]
  43. public void EventHandlerShouldNotBeKeptAlive()
  44. {
  45. bool handled = false;
  46. var source = new EventSource();
  47. AddSubscriber(source, "Event", () => handled = true);
  48. for (int c = 0; c < 10; c++)
  49. {
  50. GC.Collect();
  51. GC.Collect(3, GCCollectionMode.Forced, true);
  52. }
  53. source.Fire();
  54. Assert.False(handled);
  55. }
  56. private void AddSubscriber(EventSource source, string name, Action func)
  57. {
  58. WeakSubscriptionManager.Subscribe(source, name, new Subscriber(func));
  59. }
  60. }
  61. }