简体   繁体   English

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

[英]How to Verify assert throw exception for the return list function C#

How do I use Assert (or other Test class) to verify that an exception has been thrown?如何使用 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;
}

Unit Test In this unit test trying to capture the null reference exception单元测试在这个单元测试中试图捕获空引用异常

[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);
}

But while doing this getting this error message needs suggestion但是在执行此操作时收到此错误消息需要建议

Assert.Throws() Failure Assert.Throws() 失败
Expected: typeof(System.Exception)预期:typeof(System.Exception)
Actual: (No exception was thrown)实际:(没有抛出异常)

使用ThrowsAsync而不是Throws

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

I assume because you catch the exception in the target method named " HHABranchAggregatorDetails ", the Assert API doesn't notice it.我假设因为您在名为“ HHABranchAggregatorDetails ”的目标方法中捕获了异常,所以 Assert API 不会注意到它。 You would need to either not catch or to rethrow it, I guess.我想你要么不抓住它要么重新扔掉它。

But of course its better in productive code to catch it ^^但当然它在生产代码中更好地捕捉它^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM