Skip to content

Commit 0b15992

Browse files
committed
Add unit test for [AlsoValidateProperty]
1 parent 3191845 commit 0b15992

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

tests/CommunityToolkit.Mvvm.UnitTests/Test_ObservablePropertyAttribute.cs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,13 +224,46 @@ public void Test_ObservablePropertyWithValueNamedField_WithValidationAttributes(
224224

225225
model.PropertyChanged += (s, e) => propertyNames.Add(e.PropertyName);
226226

227+
bool errorsChanged = false;
228+
229+
model.ErrorsChanged += (s, e) => errorsChanged = true;
230+
227231
model.Value = "Hello world";
228232

229233
Assert.AreEqual(model.Value, "Hello world");
230234

235+
// The [AlsoValidateProperty] attribute wasn't used, so the property shouldn't be validated
236+
Assert.IsFalse(errorsChanged);
237+
231238
CollectionAssert.AreEqual(new[] { nameof(model.Value) }, propertyNames);
232239
}
233240

241+
[TestMethod]
242+
public void Test_ObservablePropertyWithValueNamedField_WithValidationAttributesAndValidation()
243+
{
244+
ModelWithValuePropertyWithAutomaticValidation model = new();
245+
246+
List<string?> propertyNames = new();
247+
248+
model.PropertyChanged += (s, e) => propertyNames.Add(e.PropertyName);
249+
250+
List<DataErrorsChangedEventArgs> errors = new();
251+
252+
model.ErrorsChanged += (s, e) => errors.Add(e);
253+
254+
model.Value = "Bo";
255+
256+
Assert.IsTrue(model.HasErrors);
257+
Assert.AreEqual(errors.Count, 1);
258+
Assert.AreEqual(errors[0].PropertyName, nameof(ModelWithValuePropertyWithAutomaticValidation.Value));
259+
260+
model.Value = "Hello world";
261+
262+
Assert.IsFalse(model.HasErrors);
263+
Assert.AreEqual(errors.Count, 2);
264+
Assert.AreEqual(errors[1].PropertyName, nameof(ModelWithValuePropertyWithAutomaticValidation.Value));
265+
}
266+
234267
// See https://github.com/CommunityToolkit/WindowsCommunityToolkit/issues/4184
235268
[TestMethod]
236269
public void Test_GeneratedPropertiesWithValidationAttributesOverFields()
@@ -893,6 +926,15 @@ public partial class ModelWithValuePropertyWithValidation : ObservableValidator
893926
private string? value;
894927
}
895928

929+
public partial class ModelWithValuePropertyWithAutomaticValidation : ObservableValidator
930+
{
931+
[ObservableProperty]
932+
[Required]
933+
[MinLength(5)]
934+
[AlsoValidateProperty]
935+
private string? value;
936+
}
937+
896938
public partial class ViewModelWithValidatableGeneratedProperties : ObservableValidator
897939
{
898940
[Required]

0 commit comments

Comments
 (0)