Created
October 22, 2016 16:09
-
-
Save bymyslf/2fe2b0b21eed62f576cf5ba460e791d5 to your computer and use it in GitHub Desktop.
Model binder unit test base class
This file contains 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 System.Collections.Specialized; | |
using System.Web; | |
using System.Web.Mvc; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
using Moq; | |
//http://mdavies.net/2013/06/07/unit-testing-mvc3mvc4-model-binders/ | |
public abstract class ModelBinderTestsBase<TBinder, TModel> | |
where TBinder : IModelBinder, new() | |
{ | |
private ControllerContext controllerContext; | |
private ModelBindingContext bindingContext; | |
private NameValueCollection valuesCollection; | |
[TestInitialize] | |
public virtual void TestInitialize() | |
{ | |
this.SetupControllerContext(); | |
this.SetValues(new NameValueCollection()); | |
} | |
protected Mock<HttpRequestBase> HttpRequestMock { get; private set; } | |
protected Mock<HttpContextBase> HttpContextMock { get; private set; } | |
protected ControllerContext ControllerContext { get { return this.controllerContext; } } | |
protected ModelBindingContext BindingContext { get { return this.bindingContext; } } | |
protected void SetValues(NameValueCollection valuesCollection) | |
{ | |
this.HttpRequestMock.SetupGet(p => p.Form).Returns(valuesCollection); | |
} | |
protected TModel BindModel() | |
{ | |
this.SetupBindingContext(); | |
return (TModel)new TBinder().BindModel(this.controllerContext, this.bindingContext); | |
} | |
protected virtual void SetupControllerContext() | |
{ | |
this.HttpRequestMock = new Mock<HttpRequestBase>(); | |
this.HttpContextMock = new Mock<HttpContextBase>(); | |
this.controllerContext = new ControllerContext(); | |
this.controllerContext.HttpContext = this.HttpContextMock.Object; | |
} | |
protected virtual void SetupBindingContext() | |
{ | |
var valueProvider = new NameValueCollectionValueProvider(this.HttpRequestMock.Object.Form, null); | |
var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TBinder)); | |
this.bindingContext = new ModelBindingContext | |
{ | |
ModelName = typeof(TModel).Name, | |
ValueProvider = valueProvider, | |
ModelMetadata = modelMetadata | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment