MockEnumerable.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Collections.Generic;
  6. using Microsoft.Reactive.Testing;
  7. namespace ReactiveTests
  8. {
  9. public class MockEnumerable<T> : IEnumerable<T>
  10. {
  11. public readonly TestScheduler Scheduler;
  12. public readonly List<Subscription> Subscriptions = new();
  13. private readonly IEnumerable<T> _underlyingEnumerable;
  14. public MockEnumerable(TestScheduler scheduler, IEnumerable<T> underlyingEnumerable)
  15. {
  16. Scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
  17. _underlyingEnumerable = underlyingEnumerable ?? throw new ArgumentNullException(nameof(underlyingEnumerable));
  18. }
  19. public IEnumerator<T> GetEnumerator()
  20. {
  21. return new MockEnumerator(Scheduler, Subscriptions, _underlyingEnumerable.GetEnumerator());
  22. }
  23. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  24. {
  25. return GetEnumerator();
  26. }
  27. private class MockEnumerator : IEnumerator<T>
  28. {
  29. private readonly List<Subscription> _subscriptions;
  30. private readonly IEnumerator<T> _enumerator;
  31. private readonly TestScheduler _scheduler;
  32. private readonly int _index;
  33. private bool _disposed;
  34. public MockEnumerator(TestScheduler scheduler, List<Subscription> subscriptions, IEnumerator<T> enumerator)
  35. {
  36. _subscriptions = subscriptions;
  37. _enumerator = enumerator;
  38. _scheduler = scheduler;
  39. _index = subscriptions.Count;
  40. subscriptions.Add(new Subscription(scheduler.Clock));
  41. }
  42. public T Current
  43. {
  44. get
  45. {
  46. if (_disposed)
  47. {
  48. throw new ObjectDisposedException("this");
  49. }
  50. return _enumerator.Current;
  51. }
  52. }
  53. public void Dispose()
  54. {
  55. if (!_disposed)
  56. {
  57. _disposed = true;
  58. _enumerator.Dispose();
  59. _subscriptions[_index] = new Subscription(_subscriptions[_index].Subscribe, _scheduler.Clock);
  60. }
  61. }
  62. object System.Collections.IEnumerator.Current
  63. {
  64. get { return Current; }
  65. }
  66. public bool MoveNext()
  67. {
  68. if (_disposed)
  69. {
  70. throw new ObjectDisposedException("this");
  71. }
  72. return _enumerator.MoveNext();
  73. }
  74. public void Reset()
  75. {
  76. if (_disposed)
  77. {
  78. throw new ObjectDisposedException("this");
  79. }
  80. _enumerator.Reset();
  81. }
  82. }
  83. }
  84. }