From 62978229c4271092d274531623ba87bc1765d2e7 Mon Sep 17 00:00:00 2001 From: Doug Bunting Date: Fri, 20 Nov 2015 10:26:09 -0800 Subject: [PATCH] Ease unit testing of `Controller.TryValidateModel()` - #3586 - reverse conditions to access `_options.Value` only when test has set up an `IStringLocalizerFactory` --- .../DataAnnotationsModelValidatorProvider.cs | 4 +++- .../ControllerTest.cs | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.AspNet.Mvc.DataAnnotations/DataAnnotationsModelValidatorProvider.cs b/src/Microsoft.AspNet.Mvc.DataAnnotations/DataAnnotationsModelValidatorProvider.cs index 719b1e3a39..7f62e9624c 100644 --- a/src/Microsoft.AspNet.Mvc.DataAnnotations/DataAnnotationsModelValidatorProvider.cs +++ b/src/Microsoft.AspNet.Mvc.DataAnnotations/DataAnnotationsModelValidatorProvider.cs @@ -2,7 +2,9 @@ // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.ComponentModel.DataAnnotations; +#if DOTNET5_4 using System.Reflection; +#endif using Microsoft.Extensions.Localization; using Microsoft.Extensions.OptionsModel; @@ -34,7 +36,7 @@ namespace Microsoft.AspNet.Mvc.ModelBinding.Validation public void GetValidators(ModelValidatorProviderContext context) { IStringLocalizer stringLocalizer = null; - if (_options.Value.DataAnnotationLocalizerProvider != null && _stringLocalizerFactory != null) + if (_stringLocalizerFactory != null && _options.Value.DataAnnotationLocalizerProvider != null) { stringLocalizer = _options.Value.DataAnnotationLocalizerProvider( context.ModelMetadata.ContainerType ?? context.ModelMetadata.ModelType, diff --git a/test/Microsoft.AspNet.Mvc.ViewFeatures.Test/ControllerTest.cs b/test/Microsoft.AspNet.Mvc.ViewFeatures.Test/ControllerTest.cs index 79d43f9168..2248216997 100644 --- a/test/Microsoft.AspNet.Mvc.ViewFeatures.Test/ControllerTest.cs +++ b/test/Microsoft.AspNet.Mvc.ViewFeatures.Test/ControllerTest.cs @@ -1770,6 +1770,22 @@ namespace Microsoft.AspNet.Mvc.Test Assert.Equal("Out of range!", error.ErrorMessage); } + [Fact] + public void TryValidateModel_Succeeds_WithoutValidatorMetadata() + { + // Arrange + // Do not add a Mock validator provider to this test. Test is intended to demonstrate ease of unit testing + // and exercise DataAnnotationsModelValidatorProvider, avoiding #3586 regressions. + var model = new TryValidateModelModel(); + var controller = GetController(binder: null, provider: null); + + // Act + var result = controller.TryValidateModel(model); + + // Assert + Assert.True(controller.ModelState.IsValid); + } + [Fact] public void TryValidateModelEmptyBindingContextThrowsException() {