【发布时间】: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