MockEnumerable.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
  2. using System.Collections.Generic;
  3. using System.Reactive.Concurrency;
  4. using Microsoft.Reactive.Testing;
  5. using System;
  6. namespace ReactiveTests
  7. {
  8. public class MockEnumerable<T> : IEnumerable<T>
  9. {
  10. public readonly TestScheduler Scheduler;
  11. public readonly List<Subscription> Subscriptions = new List<Subscription>();
  12. IEnumerable<T> underlyingEnumerable;
  13. public MockEnumerable(TestScheduler scheduler, IEnumerable<T> underlyingEnumerable)
  14. {
  15. if (scheduler == null)
  16. throw new ArgumentNullException("scheduler");
  17. if (underlyingEnumerable == null)
  18. throw new ArgumentNullException("underlyingEnumerable");
  19. this.Scheduler = scheduler;
  20. this.underlyingEnumerable = underlyingEnumerable;
  21. }
  22. public IEnumerator<T> GetEnumerator()
  23. {
  24. return new MockEnumerator(Scheduler, Subscriptions, underlyingEnumerable.GetEnumerator());
  25. }
  26. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  27. {
  28. return GetEnumerator();
  29. }
  30. class MockEnumerator : IEnumerator<T>
  31. {
  32. List<Subscription> subscriptions;
  33. IEnumerator<T> enumerator;
  34. TestScheduler scheduler;
  35. int index;
  36. bool disposed = false;
  37. public MockEnumerator(TestScheduler scheduler, List<Subscription> subscriptions, IEnumerator<T> enumerator)
  38. {
  39. this.subscriptions = subscriptions;
  40. this.enumerator = enumerator;
  41. this.scheduler = scheduler;
  42. index = subscriptions.Count;
  43. subscriptions.Add(new Subscription(scheduler.Clock));
  44. }
  45. public T Current
  46. {
  47. get
  48. {
  49. if (disposed)
  50. throw new ObjectDisposedException("this");
  51. return enumerator.Current;
  52. }
  53. }
  54. public void Dispose()
  55. {
  56. if (!disposed)
  57. {
  58. disposed = true;
  59. enumerator.Dispose();
  60. subscriptions[index] = new Subscription(subscriptions[index].Subscribe, scheduler.Clock);
  61. }
  62. }
  63. object System.Collections.IEnumerator.Current
  64. {
  65. get { return Current; }
  66. }
  67. public bool MoveNext()
  68. {
  69. if (disposed)
  70. throw new ObjectDisposedException("this");
  71. return enumerator.MoveNext();
  72. }
  73. public void Reset()
  74. {
  75. if (disposed)
  76. throw new ObjectDisposedException("this");
  77. enumerator.Reset();
  78. }
  79. }
  80. }
  81. }