【发布时间】:2021-11-20 10:52:03
【问题描述】:
我有以下方法:
public TryAsync<bool> TryRelay(
MontageUploadConfig montageData,
File sourceFile,
CancellationToken cancellationToken
) => new(async () =>
{
byte[] fileContent = await _httpClient.GetByteArrayAsync(sourceFile.Url, cancellationToken);
return await _attachmentController.TryUploadAttachment(montageData.EventId, fileContent, sourceFile.Name);
});
我创建了几个测试来证明它按预期工作。 我对阴性案例的测试失败了。
这是测试:
[Fact]
public static async Task TestRelayShouldCatchErrorsGettingFile()
{
// Arrange
Mock<IAttachmentControllerV6> mockAttachmentController = new();
Mock<HttpMessageHandler> mockHttpMessageHandler = new();
MontageUploadTaskProcessor mockProcessorUnderTest = CreateProcessor(mockAttachmentController, mockHttpMessageHandler);
MontageUploadConfig montageData = new()
{
EventId = "Test001"
};
File sourceFile = new()
{
Name = "Test.pdf",
Url = "https://www.example.com/test.pdf"
};
CancellationToken cancellationToken = default;
const string message = "Expected Exception";
mockHttpMessageHandler.SetupAnyRequest()
.Throws(new SalesforceCacheException(message));
// Act
Result<bool> result = await mockProcessorUnderTest.TryRelay(montageData, sourceFile, cancellationToken)();
// Assert
Assert.True(result.IsFaulted);
result.IfFail(exception =>
{
Assert.True(exception is Exception);
Assert.Equal(message, exception.Message);
});
}
这是错误:
WorkflowTests.TaskProcessor.OldOrg.MontageUploadTaskProcessorUnitTests.TestRelayShouldCatchErrorsGettingFile 资料来源:MontageUploadTaskProcessorUnitTests.cs 第 59 行持续时间: 144 毫秒
消息:SFCacheController.SalesforceCacheException:预期 例外
堆栈跟踪:ThrowException.Execute(Invocation invocation) 第 22 行 MethodCall.ExecuteCore(调用调用)第 97 行 Setup.Execute(调用调用)第 85 行 FindAndExecuteMatchingSetup.Handle(Invocation 调用,Mock mock) 第 107 行 IInterceptor.Intercept(Invocation 调用) 第 17 行 Interceptor.Intercept(IInvocation 底层) 第 107 行 AbstractInvocation.Proceed() HttpMessageHandlerProxy.SendAsync(HttpRequestMessage 请求, CancellationToken 取消令牌) HttpMessageInvoker.SendAsync(HttpRequestMessage 请求, CancellationToken 取消令牌) HttpClient.SendAsyncCore(HttpRequestMessage 请求, HttpCompletionOption 完成选项,布尔异步,布尔 emitTelemetryStartStop, CancellationToken cancelToken) HttpClient.GetByteArrayAsyncCore(HttpRequestMessage 请求, CancellationToken cancelToken)
d.MoveNext() 行 140 --- 来自先前位置的堆栈跟踪结束 --- MontageUploadTaskProcessorUnitTests.TestRelayShouldCatchErrorsGettingFile() 第 81 行 --- 上一个位置的堆栈跟踪结束 ---
异常似乎是在调用TryRelay() 之后引发的,甚至在尝试任何断言之前。
我期望TryAsync 会捕获并装箱异常是不是错了?
我期望这在测试环境中工作是错误的吗?
我需要做什么才能通过此测试?
【问题讨论】:
-
您最近获得并接受的这个答案 (stackoverflow.com/a/69358330/5311735) 不是讨论了完全相同的问题吗?
-
它讨论了这个问题,但介于两者之间的某个地方试图实际创建一个单元测试来证明功能并防止回归,我意识到我遗漏了一些东西......我希望它在测试中一边。
-
你仍然使用错误的方法(
new(async () => ...)来创建 TryAsync,你没有使用库提供的函数LanguageExt.Prelude.TryAsync。 -
我以为我改变了...会再试一次,谢谢。 :-)
-
@Evk,这就是问题所在。谢谢!
标签: c# functional-programming moq xunit try-type