C# 如何在C中模拟抛出特定异常的方法#
我试图模拟一个方法来抛出一个特定的异常,但无法实现。我的方法看起来像-C# 如何在C中模拟抛出特定异常的方法#,c#,mocking,C#,Mocking,我试图模拟一个方法来抛出一个特定的异常,但无法实现。我的方法看起来像- try { if (!ledgerStoreRequest.LedgerSummary.IsNullOrEmpty()) { await _ledgerStoreHelper.WriteLedgerSummary(ledgerStoreRequest, ref storedSummaryCount, businessUnitId); }
try
{
if (!ledgerStoreRequest.LedgerSummary.IsNullOrEmpty())
{
await _ledgerStoreHelper.WriteLedgerSummary(ledgerStoreRequest, ref storedSummaryCount, businessUnitId);
}
}
catch (ArgumentException exception)
{
var errorMessage = $"Error: DynamoDB insertion has failed with duplicate key. {exception.Message}";
_logger.LogError($"{errorMessage}");
throw new Ascendon.SDK.Contract.Fault.InvalidPropertyException(new Fault
{
Code = AccountErrorCode.InsertionToLedgerSummaryTblFailed,
Message = $"LedgerStore API failure. DynamoDB insertion has failed for " +
$"BusinessUnit: {businessUnitId} SubscriberID: {ledgerStoreRequest.SubscriberId}."
});
}
因此,我试图模拟WriteLedgerSummary,以在单元测试中返回InvalidPropertyException。目前我的做法是-
// Arrange
LedgerStoreHelper
.Setup(m =>
m.WriteLedgerSummary(It.Ref<LedgerStoreRequest>.IsAny, ref It.Ref<int>.IsAny, It.Ref<int>.IsAny))
.Throws(new InvalidPropertyException(new Fault
{
Code = GlobalErrorCode.InvalidProperty,
Message = "some error"
}));
// Act
var response = Assert.ThrowsAsync<InvalidPropertyException>(() =>
_repository.StoreLedgerEntityAsync(BusinessUnitId,
LedgerStoreTestConstants.LedgerStoreRequestInvoiceSummaryItem));
//排列
分类库助手
.设置(m=>
m、 WriteLedgerSummary(It.Ref.IsAny,Ref It.Ref.IsAny,It.Ref.IsAny))
.Throws(新的InvalidPropertyException(新故障
{
代码=GlobalErrorCode.InvalidProperty,
Message=“一些错误”
}));
//表演
var response=Assert.ThrowsAsync(()=>
_repository.StoreLedgerEntityAsync(BusinessUnitId,
LedgerStoreTestConstants.LedgerStoreRequestInvoiceSummaryItem));
但无法看到响应中的异常。我在这里遗漏了什么吗?您使用哪种模拟框架?
WriteLedgerSummary()
似乎是async
,因为您正在等待它。您需要将模拟设置为异步吗?例如,Moq使用ThrowsAsync()
。我使用Moq framework@somebody,这是因为使用ThrowsAsync()而不是ThrowsAsync()吗@martincostelloi如果您使用的是Moq,则使用ThrowsAsync()
。