0

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

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.Throws()
预期失败:typeof(System.Exception)
实际:(未引发异常)

4

2 回答 2

1

使用ThrowsAsync代替Throws

var ex = await Assert.ThrowsAsync<Exception>(async () => await agencyConfigurations.HHABranchAggregatorDetails(1, 1, 3052));
于 2021-07-01T18:22:31.933 回答
0

我假设因为您在名为“”的目标方法中捕获了异常HHABranchAggregatorDetails,所以 Assert API 不会注意到它。我猜你要么不抓,要么重新扔。

但是当然它在生产代码中更好地捕捉它^^

于 2021-07-01T18:40:18.070 回答