ExceptionValidationPluginTests.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.Collections.Generic;
  5. using System.Reactive.Linq;
  6. using Avalonia.Data;
  7. using Avalonia.Data.Core.Plugins;
  8. using Avalonia.UnitTests;
  9. using Xunit;
  10. namespace Avalonia.Base.UnitTests.Data.Core.Plugins
  11. {
  12. public class ExceptionValidationPluginTests
  13. {
  14. [Fact]
  15. public void Produces_BindingNotifications()
  16. {
  17. var inpcAccessorPlugin = new InpcPropertyAccessorPlugin();
  18. var validatorPlugin = new ExceptionValidationPlugin();
  19. var data = new Data();
  20. var accessor = inpcAccessorPlugin.Start(new WeakReference(data), nameof(data.MustBePositive));
  21. var validator = validatorPlugin.Start(new WeakReference(data), nameof(data.MustBePositive), accessor);
  22. var result = new List<object>();
  23. validator.Subscribe(x => result.Add(x));
  24. validator.SetValue(5, BindingPriority.LocalValue);
  25. validator.SetValue(-2, BindingPriority.LocalValue);
  26. validator.SetValue(6, BindingPriority.LocalValue);
  27. Assert.Equal(new[]
  28. {
  29. new BindingNotification(0),
  30. new BindingNotification(5),
  31. new BindingNotification(new ArgumentOutOfRangeException("value"), BindingErrorType.DataValidationError),
  32. new BindingNotification(6),
  33. }, result);
  34. GC.KeepAlive(data);
  35. }
  36. public class Data : NotifyingBase
  37. {
  38. private int _mustBePositive;
  39. public int MustBePositive
  40. {
  41. get { return _mustBePositive; }
  42. set
  43. {
  44. if (value <= 0)
  45. {
  46. throw new ArgumentOutOfRangeException(nameof(value));
  47. }
  48. if (value != _mustBePositive)
  49. {
  50. _mustBePositive = value;
  51. RaisePropertyChanged();
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }