AvaloniaObjectTests_Validation.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Reactive.Subjects;
  3. using Avalonia.Controls;
  4. using Xunit;
  5. namespace Avalonia.Base.UnitTests
  6. {
  7. public class AvaloniaObjectTests_Validation
  8. {
  9. [Fact]
  10. public void Registration_Throws_If_DefaultValue_Fails_Validation()
  11. {
  12. Assert.Throws<ArgumentException>(() =>
  13. new StyledProperty<int>(
  14. "BadDefault",
  15. typeof(Class1),
  16. new StyledPropertyMetadata<int>(101),
  17. validate: Class1.ValidateFoo));
  18. }
  19. [Fact]
  20. public void Metadata_Override_Throws_If_DefaultValue_Fails_Validation()
  21. {
  22. Assert.Throws<ArgumentException>(() => Class1.FooProperty.OverrideDefaultValue<Class2>(101));
  23. }
  24. [Fact]
  25. public void SetValue_Throws_If_Fails_Validation()
  26. {
  27. var target = new Class1();
  28. Assert.Throws<ArgumentException>(() => target.SetValue(Class1.FooProperty, 101));
  29. }
  30. [Fact]
  31. public void SetValue_Throws_If_Fails_Validation_Attached()
  32. {
  33. var target = new Class1();
  34. Assert.Throws<ArgumentException>(() => target.SetValue(Class1.AttachedProperty, 101));
  35. }
  36. [Fact]
  37. public void Reverts_To_DefaultValue_If_Binding_Fails_Validation()
  38. {
  39. var target = new Class1();
  40. var source = new Subject<int>();
  41. target.Bind(Class1.FooProperty, source);
  42. source.OnNext(150);
  43. Assert.Equal(11, target.GetValue(Class1.FooProperty));
  44. }
  45. [Fact]
  46. public void Reverts_To_DefaultValue_Even_In_Presence_Of_Other_Bindings()
  47. {
  48. var target = new Class1();
  49. var source1 = new Subject<int>();
  50. var source2 = new Subject<int>();
  51. target.Bind(Class1.FooProperty, source1);
  52. target.Bind(Class1.FooProperty, source2);
  53. source1.OnNext(42);
  54. source2.OnNext(150);
  55. Assert.Equal(11, target.GetValue(Class1.FooProperty));
  56. }
  57. private class Class1 : AvaloniaObject
  58. {
  59. public static readonly StyledProperty<int> FooProperty =
  60. AvaloniaProperty.Register<Class1, int>(
  61. "Qux",
  62. defaultValue: 11,
  63. validate: ValidateFoo);
  64. public static readonly AttachedProperty<int> AttachedProperty =
  65. AvaloniaProperty.RegisterAttached<Class1, Class1, int>(
  66. "Attached",
  67. defaultValue: 11,
  68. validate: ValidateFoo);
  69. public static bool ValidateFoo(int value)
  70. {
  71. return value < 100;
  72. }
  73. }
  74. private class Class2 : AvaloniaObject
  75. {
  76. }
  77. }
  78. }