// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Web.Http.Controllers; using System.Web.Http.Metadata.Providers; using System.Web.Http.Util; using Moq; using Xunit; namespace System.Web.Http.ModelBinding.Binders { public class DictionaryModelBinderTest { [Fact] public void BindModel() { // Arrange Mock mockKvpBinder = new Mock(); ModelBindingContext bindingContext = new ModelBindingContext { ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(IDictionary)), ModelName = "someName", ValueProvider = new SimpleHttpValueProvider { { "someName[0]", new KeyValuePair(42, "forty-two") }, { "someName[1]", new KeyValuePair(84, "eighty-four") } } }; HttpActionContext context = ContextUtil.CreateActionContext(); context.ControllerContext.Configuration.Services.Replace(typeof(ModelBinderProvider), (new SimpleModelBinderProvider(typeof(KeyValuePair), mockKvpBinder.Object))); mockKvpBinder .Setup(o => o.BindModel(context, It.IsAny())) .Returns((HttpActionContext cc, ModelBindingContext mbc) => { mbc.Model = mbc.ValueProvider.GetValue(mbc.ModelName).ConvertTo(mbc.ModelType); return true; }); // Act bool retVal = new DictionaryModelBinder().BindModel(context, 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]); } } }