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

所以我有这个模型:

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


这就是Web服务的操作:

  [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编写单元测试?

最佳答案

我找出原因了。这不是因为我无法将对象分配给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));
    }

关于c# - [frombody]数据绑定(bind)的写入单元测试返回空C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48614217/

10-11 04:01
查看更多