如何使用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
相关产品推荐
相关产品推荐

