// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Web.Mvc; using Microsoft.Web.UnitTestUtil; using Moq; using Xunit; namespace Microsoft.Web.Mvc.ModelBinding.Test { public class DictionaryModelBinderTest { [Fact] public void BindModel() { // Arrange ControllerContext controllerContext = new ControllerContext(); ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext { ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary)), ModelName = "someName", ModelBinderProviders = new ModelBinderProviderCollection(), ValueProvider = new SimpleValueProvider { { "someName[0]", new KeyValuePair(42, "forty-two") }, { "someName[1]", new KeyValuePair(84, "eighty-four") } } }; Mock mockKvpBinder = new Mock(); mockKvpBinder .Setup(o => o.BindModel(controllerContext, It.IsAny())) .Returns( delegate(ControllerContext cc, ExtensibleModelBindingContext mbc) { mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType); return true; }); bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(KeyValuePair), mockKvpBinder.Object, false /* suppressPrefixCheck */); // Act bool retVal = new DictionaryModelBinder().BindModel(controllerContext, bindingContext); // Assert Assert.True(retVal); var dictionary = Assert.IsAssignableFrom>(bindingContext.Model); Assert.NotNull(dictionary); Assert.Equal(2, dictionary.Count); Assert.Equal("forty-two", dictionary[42]); Assert.Equal("eighty-four", dictionary[84]); } } }