如何验证返回列表函数C#的断言抛出异常



如何使用Assert(或其他测试类(来验证是否引发了异常?

public async Task<IEnumerable<HHABranchAggregatorConfigurationDto>> HHABranchAggregatorDetails(int HHA, int UserId, int HHA_Branch_ID)
{
IEnumerable<HHABranchAggregatorConfigurationDto> hhabranchAggregatorsettingslists = new List<HHABranchAggregatorConfigurationDto>();
try
{
var EVVVendorMasterList = await _UAEVVVendorMasterRepository._HHA_Schedule_GetUAEVVVendorMaster(HHA, UserId, "EvvVendorMasterID,VendorName,isPrimary");
}
catch (Exception e)
{
_logger.LogError(e.Message);
}
return hhabranchAggregatorsettingslists;
}

单元测试在这个单元测试中,试图捕获空引用异常

[Fact]
public async Task Agency_Configuration_Should_Throw_Exception()
{
//Arrange
_UAEVVVendorMasterRepositoryMock.Setup(x => x._HHA_Schedule_GetUAEVVVendorMaster(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<string>())).Throws<NullReferenceException>();
//Act
var hhabranchAggregatorsactuallist = await agencyConfigurations.HHABranchAggregatorDetails(1, 1, 3052);
//Assert
var ex = Assert.Throws<Exception>(() => hhabranchAggregatorsactuallist);
}

但是在这样做的时候,得到这个错误消息需要建议

Assert.Sthrows((失败
预期:typeof(System.Exception(
实际:(未引发异常(

使用ThrowsAsync而不是Throws:

var ex = await Assert.ThrowsAsync<Exception>(async () => await agencyConfigurations.HHABranchAggregatorDetails(1, 1, 3052));

我假设是因为您在名为"的目标方法中捕获了异常;CCD_ 3";,Assert API没有注意到这一点。我想您需要要么不捕获它,要么重新抛出它

但在生产代码中捕获它^^当然更好

最新更新