Я имею, записал пользовательский образцовый редактор связей в проекте, который использует ASP.NET MVC 2. Этот образцовый редактор связей связывает всего 2 поля модели:
public class TaskFormBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext,
ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "Type")
{
var value = bindingContext.ValueProvider.GetValue("Type");
var typeId = value.ConvertTo(typeof(int));
TaskType foundedType;
using (var nhSession = Domain.GetSession())
{
foundedType = nhSession.Get(typeId);
}
if (foundedType != null)
{
SetProperty(controllerContext, bindingContext, propertyDescriptor, foundedType);
}
else
{
AddModelBindError(bindingContext, propertyDescriptor);
}
return;
}
if (propertyDescriptor.Name == "Priority")
{ /* Other field binding ... */
return;
}
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
Как я могу протестировать этот образцовый редактор связей с помощью стандартного поблочного тестирования VS? Потраченный на несколько часов, гугля, найдите примеры пары (http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx), но это примеры для MVC1, и не работайте при использовании MVC2.
Я признателен за Вашу помощь.
Я модифицировал пример Hanselman's MVC 1 для тестирования связующих моделей ASP.Net MVC 2...
[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);
}
Общий подход заключается в создании имитации ControllerContext, имитации ModelBindingContext и имитации PropertyDescriptor, а затем вызове метода.
Если ваша модель связки использует другие сервисы, а она похожа на вашу (вы используете NHibernate? ), то вам придется их абстрагироваться и издеваться над ними.
Код юнит-теста будет выглядеть примерно так:
// 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
Какая проблема(ы) у вас с написанием юнит-теста?