[Test]
public async Task TestInternalHandledExceptionWithResponseDataNotReported()
{
await MockInternalServerApiException("ErrorCode:500, ErrorMessage:InternalServerError");
await MockInternalServerApiException("ErrorCode:401, ErrorMessage:Failed to verify certificate");
await MockInternalServerApiException("ErrorCode:401, ErrorMessage:Failed to retrieve certificate");
await MockInternalServerApiException("ErrorCode:400, ErrorMessage:Invalid header or payload values");
await MockInternalServerApiException("ErrorCode:1004, Errormessage:Decrypt payload failed");
await MockInternalServerApiException("ErrorCode:511, ErrorMessage:Digital signature is invalid");
await MockInternalServerApiException("ErrorCode:511, ErrorMessage:Failed to generated shared key");
await MockInternalServerApiException("Another exception should report", true);
async Task MockInternalServerApiException(string errorResponse, bool shouldReport = false)
{
var handlerMock = new Mock<HttpClientHandler>();
handlerMock.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.Throws(new ApiException(string.Empty, 500, errorResponse, null, null));
var supportMock = CreateSupportMock(handlerMock, endpointAddress: new List<(string Address, bool IsMain)>() { ("http://localhost", true), ("http://localhost:1234", false) });
var service = new CreditCheckService(supportMock.Object);
var result = await service.GetRetrospectiveMonitorAsync(new RetrospectiveMonitorRequest());
if (shouldReport)
{
supportMock.Verify(s => s.ReportDeveloperException(It.IsAny<string>(), It.IsAny<Exception>()), Times.Once);
}
else
{
supportMock.Verify(s => s.ReportDeveloperException(It.IsAny<string>(), It.IsAny<Exception>()), Times.Never);
}
}
}
C#中Moq,异步,反射相关知识
于 2022-11-16 21:12:25 首次发布
本文深入探讨了C#中的Moq库,详细讲解了如何进行单元测试和模拟对象的创建。同时,文章还涵盖了异步编程的概念,包括async/await的使用以及任务并行库(TPL)。此外,还介绍了反射的基本用法,讨论了动态类型创建、方法调用以及属性获取等关键知识点,帮助开发者更好地理解和应用C#高级特性。

2160

被折叠的 条评论
为什么被折叠?



