ActivatedSubjectTests.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Reactive.Disposables;
  5. using System.Reactive.Subjects;
  6. using Xunit;
  7. namespace Avalonia.Styling.UnitTests
  8. {
  9. public class ActivatedSubjectTests
  10. {
  11. [Fact]
  12. public void Should_Set_Values()
  13. {
  14. var activator = new BehaviorSubject<bool>(false);
  15. var source = new TestSubject();
  16. var target = new ActivatedSubject(activator, source, string.Empty);
  17. target.Subscribe();
  18. target.OnNext("bar");
  19. Assert.Equal(AvaloniaProperty.UnsetValue, source.Value);
  20. activator.OnNext(true);
  21. target.OnNext("baz");
  22. Assert.Equal("baz", source.Value);
  23. activator.OnNext(false);
  24. Assert.Equal(AvaloniaProperty.UnsetValue, source.Value);
  25. target.OnNext("bax");
  26. activator.OnNext(true);
  27. Assert.Equal("bax", source.Value);
  28. }
  29. [Fact]
  30. public void Should_Invoke_OnCompleted_On_Activator_Completed()
  31. {
  32. var activator = new BehaviorSubject<bool>(false);
  33. var source = new TestSubject();
  34. var target = new ActivatedSubject(activator, source, string.Empty);
  35. target.Subscribe();
  36. activator.OnCompleted();
  37. Assert.True(source.Completed);
  38. }
  39. [Fact]
  40. public void Should_Invoke_OnError_On_Activator_Error()
  41. {
  42. var activator = new BehaviorSubject<bool>(false);
  43. var source = new TestSubject();
  44. var target = new ActivatedSubject(activator, source, string.Empty);
  45. var targetError = default(Exception);
  46. var error = new Exception();
  47. target.Subscribe(_ => { }, e => targetError = e);
  48. activator.OnError(error);
  49. Assert.Same(error, source.Error);
  50. Assert.Same(error, targetError);
  51. }
  52. private class TestSubject : ISubject<object>
  53. {
  54. private IObserver<object> _observer;
  55. public bool Completed { get; set; }
  56. public Exception Error { get; set; }
  57. public object Value { get; set; } = AvaloniaProperty.UnsetValue;
  58. public void OnCompleted()
  59. {
  60. Completed = true;
  61. }
  62. public void OnError(Exception error)
  63. {
  64. Error = error;
  65. }
  66. public void OnNext(object value)
  67. {
  68. Value = value;
  69. }
  70. public IDisposable Subscribe(IObserver<object> observer)
  71. {
  72. _observer = observer;
  73. return Disposable.Empty;
  74. }
  75. }
  76. }
  77. }