[英]Write Unit test for [frombody] data binding returns null C#
我想为[frombody]
数据绑定编写单元测试,在C#中返回null
。
所以我有这个型号:
public class Model
{
public int number{ get; set; }
}
这就是Web服务的Action:
[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
由于Reponse
在测试控制器为null
。
所以我只是在我的测试控制器中设置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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.