Last active
November 19, 2015 07:30
-
-
Save ivaylokenov/1ef672dfbb62cb691607 to your computer and use it in GitHub Desktop.
TryValidateModel in Unit Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using Microsoft.AspNet.Http.Internal; | |
| using Microsoft.AspNet.Mvc; | |
| using Microsoft.AspNet.Mvc.Abstractions; | |
| using Microsoft.AspNet.Mvc.Formatters; | |
| using Microsoft.AspNet.Mvc.ModelBinding; | |
| using Microsoft.AspNet.Mvc.ModelBinding.Metadata; | |
| using Microsoft.AspNet.Mvc.ModelBinding.Validation; | |
| using Microsoft.AspNet.Mvc.ViewFeatures; | |
| using Microsoft.AspNet.Routing; | |
| using System; | |
| using System.Collections.Generic; | |
| using System.ComponentModel.DataAnnotations; | |
| using System.Reflection; | |
| using Xunit; | |
| namespace TestApp.Tests | |
| { | |
| public class HomeController : Controller | |
| { | |
| [HttpPost] | |
| public IActionResult Index(SomeModel model) | |
| { | |
| this.TryValidateModel(model); | |
| if (this.ModelState.IsValid) | |
| { | |
| return Ok(); | |
| } | |
| return HttpBadRequest(); | |
| } | |
| } | |
| public class SomeModel | |
| { | |
| [Required] | |
| public int Int { get; set; } | |
| [Required] | |
| [StringLength(20, MinimumLength = 5)] | |
| public string String { get; set; } | |
| } | |
| public class ControllersTest | |
| { | |
| [Fact] | |
| public void TryValidateModelTest() | |
| { | |
| var controller = GetController(new GenericModelBinder(), new CompositeValueProvider()); | |
| controller.Index(new SomeModel()); // throws null reference exception, test fails | |
| Assert.False(controller.ModelState.IsValid); | |
| } | |
| // code copied from MVC source unit tests but still throws exception | |
| private static HomeController GetController(IModelBinder binder, IValueProvider provider) | |
| { | |
| var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); | |
| var httpContext = new DefaultHttpContext(); | |
| var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); | |
| var viewData = new ViewDataDictionary(metadataProvider, new ModelStateDictionary()); | |
| var tempData = new TempDataDictionary(new HttpContextAccessor(), new SessionStateTempDataProvider()); | |
| var bindingContext = new ActionBindingContext() | |
| { | |
| ModelBinder = binder, | |
| ValueProvider = provider, | |
| InputFormatters = new List<IInputFormatter>(), | |
| ValidatorProvider = new DataAnnotationsModelValidatorProvider( | |
| options: null, | |
| stringLocalizerFactory: null) | |
| }; | |
| var contr = new HomeController() | |
| { | |
| ActionContext = actionContext, | |
| BindingContext = bindingContext, | |
| MetadataProvider = metadataProvider, | |
| ViewData = viewData, | |
| TempData = tempData, | |
| ObjectValidator = new DefaultObjectValidator(new IExcludeTypeValidationFilter[0], metadataProvider) | |
| }; | |
| return contr; | |
| } | |
| internal class TestModelMetadataProvider : DefaultModelMetadataProvider | |
| { | |
| // Creates a provider with all the defaults - includes data annotations | |
| public static IModelMetadataProvider CreateDefaultProvider() | |
| { | |
| var detailsProviders = new IMetadataDetailsProvider[] | |
| { | |
| new DefaultBindingMetadataProvider(CreateMessageProvider()), | |
| new DefaultValidationMetadataProvider(), | |
| new DataAnnotationsMetadataProvider(), | |
| // new DataMemberRequiredBindingMetadataProvider(), | |
| }; | |
| var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders); | |
| return new DefaultModelMetadataProvider(compositeDetailsProvider); | |
| } | |
| private readonly TestModelMetadataDetailsProvider _detailsProvider; | |
| public TestModelMetadataProvider() | |
| : this(new TestModelMetadataDetailsProvider()) | |
| { | |
| } | |
| private TestModelMetadataProvider(TestModelMetadataDetailsProvider detailsProvider) | |
| : base(new DefaultCompositeMetadataDetailsProvider(new IMetadataDetailsProvider[] | |
| { | |
| new DefaultBindingMetadataProvider(CreateMessageProvider()), | |
| new DefaultValidationMetadataProvider(), | |
| new DataAnnotationsMetadataProvider(), | |
| detailsProvider | |
| })) | |
| { | |
| _detailsProvider = detailsProvider; | |
| } | |
| public IMetadataBuilder ForType(Type type) | |
| { | |
| var key = ModelMetadataIdentity.ForType(type); | |
| var builder = new MetadataBuilder(key); | |
| _detailsProvider.Builders.Add(builder); | |
| return builder; | |
| } | |
| public IMetadataBuilder ForType<TModel>() | |
| { | |
| return ForType(typeof(TModel)); | |
| } | |
| public IMetadataBuilder ForProperty(Type containerType, string propertyName) | |
| { | |
| var property = containerType.GetRuntimeProperty(propertyName); | |
| Assert.NotNull(property); | |
| var key = ModelMetadataIdentity.ForProperty(property.PropertyType, propertyName, containerType); | |
| var builder = new MetadataBuilder(key); | |
| _detailsProvider.Builders.Add(builder); | |
| return builder; | |
| } | |
| public IMetadataBuilder ForProperty<TContainer>(string propertyName) | |
| { | |
| return ForProperty(typeof(TContainer), propertyName); | |
| } | |
| private static ModelBindingMessageProvider CreateMessageProvider() | |
| { | |
| return new ModelBindingMessageProvider | |
| { | |
| MissingBindRequiredValueAccessor = name => $"A value for the '{ name }' property was not provided.", | |
| MissingKeyOrValueAccessor = () => $"A value is required.", | |
| ValueMustNotBeNullAccessor = value => $"The value '{ value }' is invalid.", | |
| }; | |
| } | |
| private class TestModelMetadataDetailsProvider : | |
| IBindingMetadataProvider, | |
| IDisplayMetadataProvider, | |
| IValidationMetadataProvider | |
| { | |
| public List<MetadataBuilder> Builders { get; } = new List<MetadataBuilder>(); | |
| public void GetBindingMetadata(BindingMetadataProviderContext context) | |
| { | |
| foreach (var builder in Builders) | |
| { | |
| builder.Apply(context); | |
| } | |
| } | |
| public void GetDisplayMetadata(DisplayMetadataProviderContext context) | |
| { | |
| foreach (var builder in Builders) | |
| { | |
| builder.Apply(context); | |
| } | |
| } | |
| public void GetValidationMetadata(ValidationMetadataProviderContext context) | |
| { | |
| foreach (var builder in Builders) | |
| { | |
| builder.Apply(context); | |
| } | |
| } | |
| } | |
| public interface IMetadataBuilder | |
| { | |
| IMetadataBuilder BindingDetails(Action<BindingMetadata> action); | |
| IMetadataBuilder DisplayDetails(Action<DisplayMetadata> action); | |
| IMetadataBuilder ValidationDetails(Action<ValidationMetadata> action); | |
| } | |
| private class MetadataBuilder : IMetadataBuilder | |
| { | |
| private List<Action<BindingMetadata>> _bindingActions = new List<Action<BindingMetadata>>(); | |
| private List<Action<DisplayMetadata>> _displayActions = new List<Action<DisplayMetadata>>(); | |
| private List<Action<ValidationMetadata>> _valiationActions = new List<Action<ValidationMetadata>>(); | |
| private readonly ModelMetadataIdentity _key; | |
| public MetadataBuilder(ModelMetadataIdentity key) | |
| { | |
| _key = key; | |
| } | |
| public void Apply(BindingMetadataProviderContext context) | |
| { | |
| if (_key.Equals(context.Key)) | |
| { | |
| foreach (var action in _bindingActions) | |
| { | |
| action(context.BindingMetadata); | |
| } | |
| } | |
| } | |
| public void Apply(DisplayMetadataProviderContext context) | |
| { | |
| if (_key.Equals(context.Key)) | |
| { | |
| foreach (var action in _displayActions) | |
| { | |
| action(context.DisplayMetadata); | |
| } | |
| } | |
| } | |
| public void Apply(ValidationMetadataProviderContext context) | |
| { | |
| if (_key.Equals(context.Key)) | |
| { | |
| foreach (var action in _valiationActions) | |
| { | |
| action(context.ValidationMetadata); | |
| } | |
| } | |
| } | |
| public IMetadataBuilder BindingDetails(Action<BindingMetadata> action) | |
| { | |
| _bindingActions.Add(action); | |
| return this; | |
| } | |
| public IMetadataBuilder DisplayDetails(Action<DisplayMetadata> action) | |
| { | |
| _displayActions.Add(action); | |
| return this; | |
| } | |
| public IMetadataBuilder ValidationDetails(Action<ValidationMetadata> action) | |
| { | |
| _valiationActions.Add(action); | |
| return this; | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment