【问题标题】:Unit Testing that ModelBinder applied to MVC ActionResult parameter?ModelBinder 应用于 MVC ActionResult 参数的单元测试?
【发布时间】:2017-07-20 13:08:52
【问题描述】:

我有一个类似的控制器:

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

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

我希望它类似于测试一个属性被特定属性修饰,如下所示,但找不到如何以这种方式访问​​参数:

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

【问题讨论】:

    标签: c# asp.net-mvc unit-testing nunit moq


    【解决方案1】:

    这很简单。

    这是 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 2013-12-17
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多