【问题标题】:Write Unit test for [frombody] data binding returns null C#为 [frombody] 数据绑定编写单元测试返回 null C#
【发布时间】:2018-02-04 23:59:28
【问题描述】:

我想为 [frombody] 数据绑定编写一个单元测试,在 C# 中返回 null

所以我有这个模型:

 public class Model
    {
        public int number{ get; set; }
    }

这就是网络服务的动作:

  [HttpPost]
   public IActionResult API([FromBody]Model model)
   {     
      if (model== null)
      {
        return Json(new { error = "Could not decode request: JSON parsing failed" });
       }
     //some logic to get responsesToReturn;
     return Json(responsesToReturn);
   }

所以我使用内置的数据绑定来检查传入数据的有效性。假设客户端发送Json数字:“abc”,模型对象在数据绑定后将变为null . (因为 "abc" 不能转换为 int)

所以我想为此行为编写一个单元测试。这是我当前的测试:

 [TestClass]
public class ModelControllerTest
{
    [TestMethod]
    public void TestAPIModelIsNull()
    {
        var controller = new ModelController();
        Model model = null;
        var result = controller.API(model);
        object obj = new { error = "Could not decode request: JSON parsing failed" };
        var expectedJson = JsonConvert.SerializeObject(obj);
        Assert.AreEqual(expectedJson, result);
    }
}

我不断收到这个System.NullReferenceException: Object reference not set to an instance of an object. 错误。我猜是因为我明确地将模型设置为null,但该操作需要Model 的实例。但是在应用程序中,当请求数据无效时,数据绑定确实返回null。 所以问题是我如何为[frombody]数据绑定返回null编写单元测试?

【问题讨论】:

  • 测试看起来正确。 System.NullReferenceException: Object reference not set to an instance of an object. 在哪一行?
  • 你为什么要写这样一个测试?如果模型绑定器为您提供了一个空对象,那么它永远不会为空,并且您在控制器方法中的 if 条件将永远不会得到满足,因此拥有该 if 条件或为其编写测试没有意义?
  • @zaitsman 这个。 Model model = null; var result = controller.API(model)。好像我无法将模型设置为空。但在 Action 中,当传入无效数据时,data-binder 确实会向我返回一个 null 模型,这就是满足 if (model== null) 条件的地方。
  • @Vidmantas Blazevicius 实际上,当传入的数据无效时,我的控制器操作中的if (model== null) 确实会触发,我想在我的单元测试中对其进行测试...但是系统不允许我要明确地将模型对象设置为null..

标签: c# unit-testing data-binding


【解决方案1】:

我找到了原因。这不是因为我无法将对象分配给null。这是因为当我运行测试时,控制器中的Response.StatusCode = 400 给了我System.NullReferenceException 因为测试控制器中的Reponsenull

所以我只是在我的测试控制器中设置Response,如下所示:

 [TestMethod]
    public void TestAPIShowInfoIsNull()
    {
        //arrange
        var controller = new ShowsInfoController();
        controller.ControllerContext = new ControllerContext();
        controller.ControllerContext.HttpContext = new DefaultHttpContext();
        var response = controller.ControllerContext.HttpContext.Response;
        //act
        ShowsInfo showsInfo = null;
        var result = controller.API(showsInfo);
        //assert

        Assert.AreEqual(400, response.StatusCode);
        Assert.IsInstanceOfType(result, typeof(JsonResult));
    }

【讨论】:

  • 什么是ShowsInfo as API 需要Model
猜你喜欢
  • 1970-01-01
  • 2015-05-30
  • 1970-01-01
  • 2018-05-06
  • 2019-01-28
  • 2019-10-03
  • 2020-06-14
  • 2020-11-02
  • 2020-03-20
相关资源
最近更新 更多