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

如何在xUnit单元测试中获取ActionResult<T>返回的DTO

控制器单元测试:简洁获取返回的AccountTypeDTO方法

问题场景

我需要对控制器的GetAccountTypeById方法做单元测试,目标方法代码如下:

[HttpGet("{id}")]
public async Task<ActionResult<AccountTypeDTO>> GetAccountTypeById(string id)
{
    try
    {
        //Some stuffs
        return Ok(accountTypeDTO);
    }
    catch
    {
        //Some stuffs
        return Ok(accountTypeDTO);
    }
}

尝试过以下代码但无法成功获取目标DTO:

var returnedDTO = _accountTypesController.GetAccountTypeById(createdId).Result as OkObjectResult;

目前可用但写法繁琐的实现:

AccountTypeDTO returnedDTO =(AccountTypeDTO)((OkObjectResult)_accountTypesController.GetAccountTypeById(createdId).Result.Result).Value;

寻求更简洁的实现方式。


简洁实现方案

1. 异步测试直接提取Value

将测试方法改为异步,通过await获取控制器方法的返回结果,直接访问ActionResult<T>的Value属性即可拿到DTO:

// 测试方法需标记为async Task
var actionResult = await _accountTypesController.GetAccountTypeById(createdId);
AccountTypeDTO returnedDTO = actionResult.Value;

若需验证返回的是Ok状态,可追加断言:

Assert.IsType<OkObjectResult>(actionResult.Result);

2. 封装扩展方法复用逻辑

如果需要在多个测试中重复提取Ok结果的Value,可以封装一个扩展方法:

public static class ActionResultExtensions
{
    public static T ExtractOkValue<T>(this ActionResult<T> actionResult)
    {
        var okResult = actionResult.Result as OkObjectResult;
        return okResult != null ? (T)okResult.Value : default;
    }
}

使用时只需一行代码:

var actionResult = await _accountTypesController.GetAccountTypeById(createdId);
AccountTypeDTO returnedDTO = actionResult.ExtractOkValue<AccountTypeDTO>();

3. 结合断言工具类(以xUnit为例)

在单元测试中,可结合断言工具同时完成类型验证和值提取,既严谨又简洁:

var actionResult = await _accountTypesController.GetAccountTypeById(createdId);
var okResult = Assert.IsType<OkObjectResult>(actionResult.Result);
AccountTypeDTO returnedDTO = Assert.IsType<AccountTypeDTO>(okResult.Value);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:10:16