Unit testing custom model binder in ASP.NET MVC 2

后端 未结 2 593
暗喜
暗喜 2020-12-13 20:01

I\'ve wrote custom model binder in project, that uses ASP.NET MVC 2. This model binder bind just 2 fields of model:

public class TaskFormBinder : DefaultMode         


        
相关标签:
2条回答
  • 2020-12-13 20:30

    The general approach is to create a mock ControllerContext, mock ModelBindingContext, and mock PropertyDescriptor, and then call the method.

    If your model binder uses other services, which it looks like yours does (you're using NHibernate?), then you'll have to abstract those out and provide mocks of them as well.

    The unit test code will look something like this:

    // Arrange
    ControllerContext mockControllerContext = ...;
    ModelBindingContext mockModelBindingContext = ...;
    PropertyDescriptor mockPropertyDescriptor = ...;
    SomeService mockService = ...;
    
    TaskFormBinder taskFormBinder = new TaskFormBinder();
    taskFormBinder.Service = mockService;
    
    // Act
    taskFormBinder.BindProperty(
        mockControllerContext, mockModelBindingContext, mockPropertyDescriptor);
    
    // Assert
    // ... here you need to inspect the values in the model binding context to see that it set the right properties
    

    What problem(s) are you having writing the unit test?

    0 讨论(0)
  • 2020-12-13 20:32

    I've modified Hanselman's MVC 1 example to test ASP.Net MVC 2 model binders...

    [Test]
    public void Date_Can_Be_Pulled_Via_Provided_Month_Day_Year()
    {
        // Arrange
        var formCollection = new NameValueCollection { 
            { "foo.month", "2" },
            { "foo.day", "12" },
            { "foo.year", "1964" }
        };
    
        var valueProvider = new NameValueCollectionValueProvider(formCollection, null);
        var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(FwpUser));
    
        var bindingContext = new ModelBindingContext
        {
            ModelName = "foo",
            ValueProvider = valueProvider,
            ModelMetadata = modelMetadata
        };
    
        DateAndTimeModelBinder b = new DateAndTimeModelBinder { Month = "month", Day = "day", Year = "year" };
        ControllerContext controllerContext = new ControllerContext();
    
        // Act
        DateTime result = (DateTime)b.BindModel(controllerContext, bindingContext);
    
        // Assert
        Assert.AreEqual(DateTime.Parse("1964-02-12 12:00:00 am"), result);
    }
    
    0 讨论(0)
提交回复
热议问题