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

如何使用Moq模拟返回值为(bool, string)的异步方法?

Moq模拟返回值为Task<(bool, string)>的方法

要模拟返回Task<(bool, string)>类型的方法,只需向ReturnsAsync传入对应的值元组即可,具体写法如下:

直接传入元组字面量

这是最简洁的写法,适合简单场景:

var mockInsuranceService = new Mock<IInsuranceService>();
mockInsuranceService
    .Setup(x => x.CreatePhoneCertificate(12345, It.IsAny<CancellationToken>()))
    .ReturnsAsync((true, "证书创建成功"));

先声明元组变量再传入

如果需要复用元组结果或逻辑更复杂,可以先定义元组变量:

// 定义模拟结果元组
var mockCertificateResult = (IsSuccess: true, Message: "证书创建成功");

var mockInsuranceService = new Mock<IInsuranceService>();
mockInsuranceService
    .Setup(x => x.CreatePhoneCertificate(12345, It.IsAny<CancellationToken>()))
    .ReturnsAsync(mockCertificateResult);

模拟失败场景

只需修改元组的布尔值和提示字符串即可:

var mockInsuranceService = new Mock<IInsuranceService>();
mockInsuranceService
    .Setup(x => x.CreatePhoneCertificate(12345, It.IsAny<CancellationToken>()))
    .ReturnsAsync((false, "订单不存在,无法创建证书"));

内容的提问来源于stack exchange,提问作者M Javad Salehi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:34:57