• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# TestModelMetadataProvider类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中TestModelMetadataProvider的典型用法代码示例。如果您正苦于以下问题:C# TestModelMetadataProvider类的具体用法?C# TestModelMetadataProvider怎么用?C# TestModelMetadataProvider使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



TestModelMetadataProvider类属于命名空间,在下文中一共展示了TestModelMetadataProvider类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: GetValidators_CachesAllValidators

        public void GetValidators_CachesAllValidators()
        {
            // Arrange
            var cache = new ValidatorCache();
            var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
            var validatorProvider = TestModelValidatorProvider.CreateDefaultProvider();

            // Act - 1
            var validators1 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 1
            var attribute1 = Assert.IsType<DataAnnotationsModelValidator>(validators1[0]).Attribute;
            var attribute2 = Assert.IsType<DataAnnotationsModelValidator>(validators1[1]).Attribute;
            Assert.Contains(attribute1, metadata.ValidatorMetadata); // Copied by provider
            Assert.Contains(attribute2, metadata.ValidatorMetadata); // Copied by provider

            // Act - 2
            var validators2 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 2
            Assert.Same(validators1, validators2);

            Assert.Contains(validators1[0], validators2); // Cached
            Assert.Contains(validators1[1], validators2); // Cached
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:25,代码来源:ValidatorCacheTest.cs


示例2: GetValidators_DoesNotCacheValidatorsWithIsReusableFalse

        public void GetValidators_DoesNotCacheValidatorsWithIsReusableFalse()
        {
            // Arrange
            var cache = new ValidatorCache();
            var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
            var validatorProvider = new ProviderWithNonReusableValidators();

            // Act - 1
            var validators1 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 1
            var validator1 = Assert.IsType<DataAnnotationsModelValidator>(validators1[0]);
            var validator2 = Assert.IsType<DataAnnotationsModelValidator>(validators1[1]);
            Assert.Contains(validator1.Attribute, metadata.ValidatorMetadata); // Copied by provider
            Assert.Contains(validator2.Attribute, metadata.ValidatorMetadata); // Copied by provider

            // Act - 2
            var validators2 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 2
            Assert.NotSame(validators1, validators2);

            var requiredValidator = Assert.Single(validators2.Where(v => (v as DataAnnotationsModelValidator).Attribute is RequiredAttribute));
            Assert.Contains(requiredValidator, validators1); // cached
            var stringLengthValidator = Assert.Single(validators2.Where(v => (v as DataAnnotationsModelValidator).Attribute is StringLengthAttribute));
            Assert.DoesNotContain(stringLengthValidator, validators1); // not cached
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:27,代码来源:ValidatorCacheTest.cs


示例3: GetValidators_CachesAllValidators

        public void GetValidators_CachesAllValidators()
        {
            // Arrange
            var cache = new ClientValidatorCache();
            var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
            var validatorProvider = TestClientModelValidatorProvider.CreateDefaultProvider();

            // Act - 1
            var validators1 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 1
            var attribute1 = Assert.Single(validators1.OfType<RequiredAttributeAdapter>()).Attribute;
            var attribute2 = Assert.Single(validators1.OfType<StringLengthAttributeAdapter>()).Attribute;
            Assert.Contains(attribute1, metadata.ValidatorMetadata); // Copied by provider
            Assert.Contains(attribute2, metadata.ValidatorMetadata); // Copied by provider

            // Act - 2
            var validators2 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 2
            Assert.Same(validators1, validators2);

            Assert.Contains(validators1[0], validators2); // Cached
            Assert.Contains(validators1[1], validators2); // Cached
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:25,代码来源:ClientValidatorCacheTest.cs


示例4: GetValidators_DoesNotCacheValidatorsWithIsReusableFalse

        public void GetValidators_DoesNotCacheValidatorsWithIsReusableFalse()
        {
            // Arrange
            var cache = new ClientValidatorCache();
            var metadata = new TestModelMetadataProvider().GetMetadataForProperty(typeof(TypeWithProperty), "Property1");
            var validatorProvider = new ProviderWithNonReusableValidators();

            // Act - 1
            var validators1 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 1
            var validator1 = Assert.Single(validators1.OfType<RequiredAttributeAdapter>());
            var validator2 = Assert.Single(validators1.OfType<StringLengthAttributeAdapter>());
            Assert.Contains(validator1.Attribute, metadata.ValidatorMetadata); // Copied by provider
            Assert.Contains(validator2.Attribute, metadata.ValidatorMetadata); // Copied by provider

            // Act - 2
            var validators2 = cache.GetValidators(metadata, validatorProvider);

            // Assert - 2
            Assert.NotSame(validators1, validators2);

            Assert.Same(validator1, Assert.Single(validators2.OfType<RequiredAttributeAdapter>())); // cached
            Assert.NotSame(validator2, Assert.Single(validators2.OfType<StringLengthAttributeAdapter>())); // not cached
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:25,代码来源:ClientValidatorCacheTest.cs


示例5: Create_ForModelMetadataReadOnly_ReturnsNull

        public void Create_ForModelMetadataReadOnly_ReturnsNull()
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForProperty(
                typeof(ModelWithIntArrayProperty),
                nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = true);

            var modelMetadata = metadataProvider.GetMetadataForProperty(
                typeof(ModelWithIntArrayProperty),
                nameof(ModelWithIntArrayProperty.ArrayProperty));

            var provider = new ArrayModelBinderProvider();
            var context = new TestModelBinderProviderContext(typeof(int[]));
            context.OnCreatingBinder((m) =>
            {
                // Expect to be called with the element type to create a binder for elements.
                Assert.Equal(typeof(int), m.ModelType);
                return Mock.Of<IModelBinder>();
            });

            // Act
            var result = provider.GetBinder(context);

            // Assert
            Assert.IsType<ArrayModelBinder<int>>(result);
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:27,代码来源:ArrayModelBinderProviderTest.cs


示例6: AddValidation_CorrectValidationTypeAndOverriddenErrorMessage

        public void AddValidation_CorrectValidationTypeAndOverriddenErrorMessage()
        {
            // Arrange
            var expectedMessage = "Error message about 'DisplayId' from override.";
            var provider = new TestModelMetadataProvider();
            provider
                .ForProperty(typeof(TypeWithNumericProperty), nameof(TypeWithNumericProperty.Id))
                .BindingDetails(d => d.ModelBindingMessageProvider.ValueMustBeANumberAccessor =
                    name => $"Error message about '{ name }' from override.");
            var metadata = provider.GetMetadataForProperty(
                typeof(TypeWithNumericProperty),
                nameof(TypeWithNumericProperty.Id));

            var adapter = new NumericClientModelValidator();

            var actionContext = new ActionContext();
            var context = new ClientModelValidationContext(actionContext, metadata, provider, new AttributeDictionary());

            // Act
            adapter.AddValidation(context);

            // Assert
            Assert.Collection(
                context.Attributes,
                kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); },
                kvp => { Assert.Equal("data-val-number", kvp.Key); Assert.Equal(expectedMessage, kvp.Value); });
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:27,代码来源:NumericClientModelValidatorTest.cs


示例7: BindModel_CallsSelectedInputFormatterOnce

        public async Task BindModel_CallsSelectedInputFormatterOnce()
        {
            // Arrange
            var mockInputFormatter = new Mock<IInputFormatter>();
            mockInputFormatter.Setup(f => f.CanRead(It.IsAny<InputFormatterContext>()))
                .Returns(true)
                .Verifiable();
            mockInputFormatter.Setup(o => o.ReadAsync(It.IsAny<InputFormatterContext>()))
                              .Returns(InputFormatterResult.SuccessAsync(new Person()))
                              .Verifiable();
            var inputFormatter = mockInputFormatter.Object;

            var provider = new TestModelMetadataProvider();
            provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

            var bindingContext = GetBindingContext(
                typeof(Person),
                new[] { inputFormatter },
                metadataProvider: provider);

            var binder = new BodyModelBinder();

            // Act
            var binderResult = await binder.BindModelAsync(bindingContext);

            // Assert
            mockInputFormatter.Verify(v => v.CanRead(It.IsAny<InputFormatterContext>()), Times.Once);
            mockInputFormatter.Verify(v => v.ReadAsync(It.IsAny<InputFormatterContext>()), Times.Once);
            Assert.NotNull(binderResult);
            Assert.True(binderResult.IsModelSet);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:31,代码来源:BodyModelBinderTests.cs


示例8: GetBindingContext

        private static DefaultModelBindingContext GetBindingContext(Type modelType)
        {
            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services);
            var modelMetadata = metadataProvider.GetMetadataForType(modelType);

            var services = new ServiceCollection();
            services.AddSingleton<IService>(new Service());

            var bindingContext = new DefaultModelBindingContext
            {
                ActionContext = new ActionContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        RequestServices = services.BuildServiceProvider(),
                    }
                },
                ModelMetadata = modelMetadata,
                ModelName = "modelName",
                FieldName = "modelName",
                ModelState = new ModelStateDictionary(),
                BinderModelName = modelMetadata.BinderModelName,
                BindingSource = modelMetadata.BindingSource,
                ValidationState = new ValidationStateDictionary(),
            };

            return bindingContext;
        }
开发者ID:xuchrist,项目名称:Mvc,代码行数:29,代码来源:ServicesModelBinderTest.cs


示例9: BindModelAsync_ValueProviderContainPrefix_Succeeds

        public async Task BindModelAsync_ValueProviderContainPrefix_Succeeds()
        {
            // Arrange
            var valueProvider = new SimpleValueProvider
            {
                { "someName[0]", "42" },
                { "someName[1]", "84" },
            };

            var bindingContext = GetBindingContext(valueProvider);
            var metadataProvider = new TestModelMetadataProvider();
            bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
                typeof(ModelWithIntArrayProperty),
                nameof(ModelWithIntArrayProperty.ArrayProperty));

            var binder = new ArrayModelBinder<int>(new SimpleTypeModelBinder(typeof(int)));

            // Act
            await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.True(bindingContext.Result.IsModelSet);

            var array = Assert.IsType<int[]>(bindingContext.Result.Model);
            Assert.Equal(new[] { 42, 84 }, array);
        }
开发者ID:xuchrist,项目名称:Mvc,代码行数:26,代码来源:ArrayModelBinderTest.cs


示例10: BindModel_NoInputFormatterFound_SetsModelStateError_RespectsBinderModelName

        public async Task BindModel_NoInputFormatterFound_SetsModelStateError_RespectsBinderModelName()
        {
            // Arrange
            var provider = new TestModelMetadataProvider();
            provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

            var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider);
            bindingContext.BinderModelName = "custom";

            var binder = CreateBinder();

            // Act
            var binderResult = await binder.BindModelResultAsync(bindingContext);

            // Assert

            // Returns non-null because it understands the metadata type.
            Assert.NotNull(binderResult);
            Assert.False(binderResult.IsModelSet);
            Assert.Null(binderResult.Model);

            // Key is the bindermodelname because this was a top-level binding.
            var entry = Assert.Single(bindingContext.ModelState);
            Assert.Equal("custom", entry.Key);
            Assert.Single(entry.Value.Errors);
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:26,代码来源:BodyModelBinderTests.cs


示例11: BindModel_NoInputFormatterFound_SetsModelStateError

        public async Task BindModel_NoInputFormatterFound_SetsModelStateError()
        {
            // Arrange
            var provider = new TestModelMetadataProvider();
            provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

            var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider);

            var binder = bindingContext.OperationBindingContext.ModelBinder;

            // Act
            var binderResult = await binder.BindModelAsync(bindingContext);

            // Assert

            // Returns non-null because it understands the metadata type.
            Assert.NotNull(binderResult);
            Assert.False(binderResult.IsModelSet);
            Assert.Null(binderResult.Model);

            // Key is empty because this was a top-level binding.
            var entry = Assert.Single(bindingContext.ModelState);
            Assert.Equal(string.Empty, entry.Key);
            Assert.Single(entry.Value.Errors);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:25,代码来源:BodyModelBinderTests.cs


示例12: ProcessAsync_GeneratesExpectedOutput

        public async Task ProcessAsync_GeneratesExpectedOutput()
        {
            // Arrange
            var expectedTagName = "not-div";
            var metadataProvider = new TestModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);

            var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
            {
                ValidationSummary = ValidationSummary.All,
            };

            var expectedPreContent = "original pre-content";
            var expectedContent = "original content";
            var tagHelperContext = new TagHelperContext(
                allAttributes: new ReadOnlyTagHelperAttributeList<IReadOnlyTagHelperAttribute>(
                    Enumerable.Empty<IReadOnlyTagHelperAttribute>()),
                items: new Dictionary<object, object>(),
                uniqueId: "test",
                getChildContentAsync: useCachedResult =>
                {
                    var tagHelperContent = new DefaultTagHelperContent();
                    tagHelperContent.SetContent("Something");
                    return Task.FromResult<TagHelperContent>(tagHelperContent);
                });
            var output = new TagHelperOutput(
                expectedTagName,
                attributes: new TagHelperAttributeList
                {
                    { "class", "form-control" }
                });
            output.PreContent.SetContent(expectedPreContent);
            output.Content.SetContent(expectedContent);
            output.PostContent.SetContent("Custom Content");

            Model model = null;
            var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
            validationSummaryTagHelper.ViewContext = viewContext;

            // Act
            await validationSummaryTagHelper.ProcessAsync(tagHelperContext, output);

            // Assert
            Assert.Equal(2, output.Attributes.Count);
            var attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("class"));
            Assert.Equal("form-control validation-summary-valid", attribute.Value);
            attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("data-valmsg-summary"));
            Assert.Equal("true", attribute.Value);
            Assert.Equal(expectedPreContent, output.PreContent.GetContent());
            Assert.Equal(expectedContent, output.Content.GetContent());
            Assert.Equal("Custom Content<ul><li style=\"display:none\"></li>" + Environment.NewLine + "</ul>",
                         output.PostContent.GetContent());
            Assert.Equal(expectedTagName, output.TagName);
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:54,代码来源:ValidationSummaryTagHelperTest.cs


示例13: GetTypeNames_ReturnsExpectedResults

        public void GetTypeNames_ReturnsExpectedResults(Type fieldType, string[] expectedResult)
        {
            // Arrange
            var metadataProvider = new TestModelMetadataProvider();
            var metadata = metadataProvider.GetMetadataForType(fieldType);

            // Act
            var typeNames = TemplateRenderer.GetTypeNames(metadata, fieldType);

            // Assert
            var collectionAssertions = expectedResult.Select<string, Action<string>>(expected =>
                actual => Assert.Equal(expected, actual));
            Assert.Collection(typeNames, collectionAssertions.ToArray());
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:14,代码来源:TemplateRendererTest.cs


示例14: EnterNestedScope_CopiesProperties

        public void EnterNestedScope_CopiesProperties()
        {
            // Arrange
            var bindingContext = new DefaultModelBindingContext
            {
                Model = new object(),
                ModelMetadata = new TestModelMetadataProvider().GetMetadataForType(typeof(object)),
                ModelName = "theName",
                OperationBindingContext = new OperationBindingContext(),
                ValueProvider = new SimpleValueProvider(),
                ModelState = new ModelStateDictionary(),
            };

            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType<object>().BindingDetails(d =>
                {
                    d.BindingSource = BindingSource.Custom;
                    d.BinderType = typeof(TestModelBinder);
                    d.BinderModelName = "custom";
                });

            var newModelMetadata = metadataProvider.GetMetadataForType(typeof(object));

            // Act
            var originalBinderModelName = bindingContext.BinderModelName;
            var originalBindingSource = bindingContext.BindingSource;
            var originalModelState = bindingContext.ModelState;
            var originalOperationBindingContext = bindingContext.OperationBindingContext;
            var originalValueProvider = bindingContext.ValueProvider;

            var disposable = bindingContext.EnterNestedScope(
                modelMetadata: newModelMetadata,
                fieldName: "fieldName",
                modelName: "modelprefix.fieldName",
                model: null);

            // Assert
            Assert.Same(newModelMetadata.BinderModelName, bindingContext.BinderModelName);
            Assert.Same(newModelMetadata.BindingSource, bindingContext.BindingSource);
            Assert.Equal("fieldName", bindingContext.FieldName);
            Assert.False(bindingContext.IsTopLevelObject);
            Assert.Null(bindingContext.Model);
            Assert.Same(newModelMetadata, bindingContext.ModelMetadata);
            Assert.Equal("modelprefix.fieldName", bindingContext.ModelName);
            Assert.Same(originalModelState, bindingContext.ModelState);
            Assert.Same(originalOperationBindingContext, bindingContext.OperationBindingContext);
            Assert.Same(originalValueProvider, bindingContext.ValueProvider);

            disposable.Dispose();
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:50,代码来源:DefaultModelBindingContextTest.cs


示例15: CanCreateModel_ReturnsTrue_IfIsTopLevelObjectAndNotIsFirstChanceBinding

        public async Task CanCreateModel_ReturnsTrue_IfIsTopLevelObjectAndNotIsFirstChanceBinding(
            bool isTopLevelObject,
            bool isFirstChanceBinding,
            string binderModelName,
            string modelName,
            bool expectedCanCreate)
        {
            var mockValueProvider = new Mock<IValueProvider>();
            mockValueProvider
                .Setup(o => o.ContainsPrefixAsync(It.IsAny<string>()))
                .Returns(Task.FromResult(false));

            var metadataProvider = new TestModelMetadataProvider();
            var bindingContext = new MutableObjectBinderContext
            {
                ModelBindingContext = new ModelBindingContext
                {
                    IsTopLevelObject = isTopLevelObject,
                    IsFirstChanceBinding = isFirstChanceBinding,

                    // Random type.
                    ModelMetadata = metadataProvider.GetMetadataForType(typeof(Person)),
                    ValueProvider = mockValueProvider.Object,
                    OperationBindingContext = new OperationBindingContext
                    {
                        ValueProvider = mockValueProvider.Object,
                        MetadataProvider = metadataProvider,
                        ValidatorProvider = Mock.Of<IModelValidatorProvider>(),
                    },

                    // CanCreateModel() ignores the BinderModelName and ModelName properties.
                    BinderModelName = binderModelName,
                    ModelName = modelName,
                },
            };

            var mutableBinder = new TestableMutableObjectModelBinder();
            bindingContext.PropertyMetadata =
                mutableBinder.GetMetadataForProperties(bindingContext.ModelBindingContext).ToArray();

            // Act
            var canCreate = await mutableBinder.CanCreateModel(bindingContext);

            // Assert
            Assert.Equal(expectedCanCreate, canCreate);
        }
开发者ID:ryanbrandenburg,项目名称:Mvc,代码行数:46,代码来源:MutableObjectModelBinderTest.cs


示例16: ObjectTemplateDisplaysNullDisplayTextWhenObjectIsNull

        public void ObjectTemplateDisplaysNullDisplayTextWhenObjectIsNull()
        {
            // Arrange
            var provider = new TestModelMetadataProvider();
            provider.ForType<DefaultTemplatesUtilities.ObjectTemplateModel>().DisplayDetails(dd =>
            {
                dd.NullDisplayText = "(null value)";
            });

            var html = DefaultTemplatesUtilities.GetHtmlHelper(provider: provider);

            // Act
            var result = DefaultDisplayTemplates.ObjectTemplate(html);

            // Assert
            Assert.Equal("(null value)", HtmlContentUtilities.HtmlContentToString(result));
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:17,代码来源:DefaultDisplayTemplatesTest.cs


示例17: DisplayTextFor_ReturnsNullDisplayText_IfSetAndValueNull

        public void DisplayTextFor_ReturnsNullDisplayText_IfSetAndValueNull()
        {
            // Arrange
            var provider = new TestModelMetadataProvider();
            provider.ForType<OverriddenToStringModel>().DisplayDetails(dd =>
            {
                dd.NullDisplayText = "Null display Text";
            });

            var helper = DefaultTemplatesUtilities.GetHtmlHelper<OverriddenToStringModel>(model: null, provider: provider);

            // Act
            var result = helper.DisplayTextFor(m => m);

            // Assert
            Assert.Equal("Null display Text", result);
        }
开发者ID:4myBenefits,项目名称:Mvc,代码行数:17,代码来源:HtmlHelperDisplayTextTest.cs


示例18: BindModel_IsGreedy

        public async Task BindModel_IsGreedy()
        {
            // Arrange
            var provider = new TestModelMetadataProvider();
            provider.ForType<Person>().BindingDetails(d => d.BindingSource = BindingSource.Body);

            var bindingContext = GetBindingContext(typeof(Person), metadataProvider: provider);

            var binder = bindingContext.OperationBindingContext.ModelBinder;

            // Act
            var binderResult = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.NotNull(binderResult);
            Assert.False(binderResult.IsModelSet);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:17,代码来源:BodyModelBinderTests.cs


示例19: CreateChildBindingContext_CopiesProperties

        public void CreateChildBindingContext_CopiesProperties()
        {
            // Arrange
            var originalBindingContext = new ModelBindingContext
            {
                Model = new object(),
                ModelMetadata = new TestModelMetadataProvider().GetMetadataForType(typeof(object)),
                ModelName = "theName",
                OperationBindingContext = new OperationBindingContext(),
                ValueProvider = new SimpleValueProvider(),
                ModelState = new ModelStateDictionary(),
            };

            var metadataProvider = new TestModelMetadataProvider();
            metadataProvider.ForType<object>().BindingDetails(d =>
                {
                    d.BindingSource = BindingSource.Custom;
                    d.BinderType = typeof(TestModelBinder);
                    d.BinderModelName = "custom";
                });

            var newModelMetadata = metadataProvider.GetMetadataForType(typeof(object));
            
            // Act
            var newBindingContext = ModelBindingContext.CreateChildBindingContext(
                originalBindingContext,
                newModelMetadata,
                fieldName: "fieldName",
                modelName: "modelprefix.fieldName",
                model: null);

            // Assert
            Assert.Same(newModelMetadata.BinderModelName, newBindingContext.BinderModelName);
            Assert.Same(newModelMetadata.BinderType, newBindingContext.BinderType);
            Assert.Same(newModelMetadata.BindingSource, newBindingContext.BindingSource);
            Assert.False(newBindingContext.FallbackToEmptyPrefix);
            Assert.Equal("fieldName", newBindingContext.FieldName);
            Assert.False(newBindingContext.IsTopLevelObject);
            Assert.Null(newBindingContext.Model);
            Assert.Same(newModelMetadata, newBindingContext.ModelMetadata);
            Assert.Equal("modelprefix.fieldName", newBindingContext.ModelName);
            Assert.Same(originalBindingContext.ModelState, newBindingContext.ModelState);
            Assert.Same(originalBindingContext.OperationBindingContext, newBindingContext.OperationBindingContext);
            Assert.Same(originalBindingContext.ValueProvider, newBindingContext.ValueProvider);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:45,代码来源:ModelBindingContextTest.cs


示例20: AddModelError_ForSingleExpression_AddsExpectedException

        public void AddModelError_ForSingleExpression_AddsExpectedException()
        {
            // Arrange
            var dictionary = new ModelStateDictionary();
            var exception = new Exception();
            var provider = new TestModelMetadataProvider();
            var metadata = provider.GetMetadataForProperty(typeof(TestModel), nameof(TestModel.Text));

            // Act
            dictionary.AddModelError<TestModel>(model => model.Text, exception, metadata);

            // Assert
            var modelState = Assert.Single(dictionary);
            var modelError = Assert.Single(modelState.Value.Errors);

            Assert.Equal("Text", modelState.Key);
            Assert.Same(exception, modelError.Exception);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:18,代码来源:ModelStateDictionaryExtensionsTest.cs



注:本文中的TestModelMetadataProvider类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# TestNode类代码示例发布时间:2022-05-24
下一篇:
C# TestModel类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap