You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单元测试遇Object Reference未实例化错误 如何断言控制器返回对象属性

问题原因

你当前的写法存在类型转换错误,自然会抛出空引用异常:
控制器的GetById方法返回值是IActionResult接口类型,当你走200正常返回逻辑时,实际返回的是封装了Customer数据的OkObjectResult对象,而非直接返回Customer实例。你直接将IActionResult类型的返回值用as Customer转换,得到的结果永远是null,后续访问response.Id自然触发空引用错误。

修正后的单元测试代码
[Test] 
public void GetById_WithExistingCustomer_GetsCustomerById()
{
    var expectedCustomer = CreatRandomCustomer();
    // 注意:确保你控制器依赖的_custBizManager内部使用的是你Mock的_customerRepoMock,否则Setup不会生效
    _customerRepoMock.Setup(x =>x.GetByID(expectedCustomer.Id)).Returns(expectedCustomer);

    var result = _controller.GetById(expectedCustomer.Id);

    // 第一步:先转换为OkObjectResult,拿到外层响应对象
    Assert.IsInstanceOf<OkObjectResult>(result);
    var okResult = result as OkObjectResult;

    // 第二步:从Value属性中取出实际的Customer数据
    Assert.IsInstanceOf<Customer>(okResult.Value);
    var response = okResult.Value as Customer;

    // 第三步:逐个属性断言校验
    Assert.AreEqual(expectedCustomer.Id, response.Id);
    // 其他属性校验同理,比如:
    // Assert.AreEqual(expectedCustomer.Name, response.Name);
    // Assert.AreEqual(expectedCustomer.Phone, response.Phone);
}
额外注意事项
  • 如果你要简化重复的属性校验逻辑,也可以用反射批量对比两个Customer对象的所有公开属性值,不用逐个手写Assert
  • 务必确认依赖链的Mock正确性:你当前只Setup了仓储层的GetByID方法,要保证控制器注入的_custBizManager实例内部调用的就是你Mock的这个仓储对象,否则业务层调用仓储时会返回null,控制器最终返回404,也会导致转换OkObjectResult失败抛异常。

内容的提问来源于stack exchange,提问作者Red Cloud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:15:02