【问题标题】:Unit test standard ViewModel binder in ASP.NET CoreASP.NET Core 中的单元测试标准 ViewModel 绑定器
【发布时间】:2017-06-21 20:45:28
【问题描述】:

我有一个这样的 ViewModel:

public class BraintreeCallbackApiModel
{
    [ModelBinder(Name = "bt_signature")]
    public string Signature { get; set; }

    [ModelBinder(Name = "bt_payload")]
    public string Payload { get; set; }
}

这些值作为x-www-form-urlencoded 参数发布到控制器。我想对绑定行为进行单元测试——bt_signature 字段正确映射到Signature

我想避免使用TestServerHttpClient,因为在这种情况下不需要开销。

我查看了 GitHub 上的 ModelBinder 测试,但无法将其绑定到我的模型类。

【问题讨论】:

  • 您对测试已经测试过的部件有何期望?您是否遇到过模型绑定器失败的情况?
  • 我想对其进行测试,以便我知道是否有人删除了 ModelBinder 属性,或者在字段名称中打错了字。
  • 然后编写一个测试来检查属性和名称是否存在。
  • 是的...我想我会这样做...谢谢。

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


【解决方案1】:

正如@SirRufo 所说,在这种情况下,单元测试可能只检查ModelBinder 类是否运行良好,该类已经过 ASP.NET Core 团队的测试。

如果您想进行测试,当有人更改bt_signature 字段名称(在模型类或请求参数中)时,它会被破坏,那么您需要编写一个功能测试。因此,您需要使用TestServer 运行您的应用程序并发出真正的请求(以HttpClient 为例)。

如果感兴趣,请查看What's the difference between unit, functional, acceptance, and integration tests?

【讨论】:

  • 当然,我不打算测试ModelBinder 是否正常工作;)我不想确定这个模型的绑定配置是否正确。正如我在问题中所说,我知道我可以使用 TestServer 做到这一点,但想通过单元测试使其更轻...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多