ModelBinder 应用于 MVC ActionResult 参数的单元测试?

Unit Testing that ModelBinder applied to MVC ActionResult parameter?

我有一个这样的控制器:

public ActionResult Index([ModelBinder(typeof(MyBinder))]int? MyId)

我想创建一个单元测试 via Nunit+Moq+AutoFixture 以确保 MyId 参数用 MyBinder 修饰,这似乎是一个有效的单元测试,因为如果它被删除,代码将按预期停止工作.显然,实际 Custom Model Binder 的测试是单独进行的。

我预计它会类似于测试 属性 装饰有特定属性,如下所示,但找不到如何以这种方式访问​​参数:

private readonly PropertyInfo _SomeProp = typeof(AddressViewModel).GetProperty("SomeProp");<br>
_SomeProp.Should().BeDecoratedWith&lt;DisplayAttribute&gt;();

这很简单。

这是 MVC 网络应用:

  public class MyBinder : IModelBinder
  {
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
      return default(int);
    }
  }

  public class DefaultController : Controller
  {
    public ActionResult Index([ModelBinder(typeof(MyBinder))] int? MyId)
    {
      return null;
    }
  }

这是我们的 NUnit 测试:

[Test]
public void Index_HasParamWithBinderAttribute()
{
  var targetType = typeof(DefaultController);
  var targetAction = targetType.GetMethod("Index", BindingFlags.Instance | BindingFlags.Public); // if there is an exception below, someone removed action from the controller

  var targetParams = targetAction.GetParameters().FirstOrDefault(x => x.Name == "MyId"); // if there is an exception below, then someone renamed the action argument

  Assert.That(targetParams.ParameterType, Is.EqualTo(typeof(int?))); // if this fails, then someone changed the type of parameter
  Assert.That((targetParams.GetCustomAttributes(true).FirstOrDefault() as ModelBinderAttribute).BinderType, Is.EqualTo(typeof(MyBinder))); // if this fails, then either there is no more a modelbinder or the type is wrong
}