0

对于 .Net Core 3.1 WebApi 项目,我想测试我的应用程序的完整管道,同时模拟外部调用(不是单元测试,完整测试)。此应用使用 Refit SDK 为外部调用注入 SDK。我希望能够在此测试中覆盖 SDK,以便到达所有代码,但根据请求的内容返回动态响应。当我使用richardszalay.mockhttp 进行测试时,如果它可以满足我的需要,我非常愿意切换嘲笑者。

我知道我可以根据请求中的值有不同的期望(我的示例中只有伪代码)。所以我能走到这一步。

不过,我需要的是,对于这个特定的工作流程,服务将在通过请求传入的响应中返回一个 ReferenceId 值。当基于请求中的 ReferenceId 字段时,关于如何在响应中动态创建 ReferenceId 字段有什么想法吗?这根本不可能吗?

 using var mockHttp = new MockHttpMessageHandler(); 
        var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp };           
        mockHttp.Expect(HttpMethod.Post, "https://api.github.com/junk/url/example").With(req => req.PaymentId == 4).Respond(resp => responseMessage);
        var apiServiceMock = RestService.For<IRealTimePayment>("https://api.github.com", settings);
        return await apiServiceMock.InitiatePaymentAsync(request: request, headers: null).ConfigureAwait(false);
4

1 回答 1

0

显然我只需要橡皮鸭。我能够通过这个代码片段实现我的目标,因为下一个可怜的灵魂试图解决这个问题。

using var mockHttp = new MockHttpMessageHandler(); 
var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp };
TransactionRequestVM requestVal = null;
mockHttp.Expect(HttpMethod.Post, "https://api.github.com/cashpro/payments/v2/payment-initiations")
    .With(m =>
    {
        async Task<bool> T()
        {
            using var requestBody = await m.Content.ReadAsStreamAsync();
            requestVal = await JsonSerializer.DeserializeAsync<TransactionRequestVM>(requestBody, new JsonSerializerOptions { PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase });
            return requestVal.PaymentIdentification.EndToEndIdentification.Equals("E2E1");
        }
        return T().Result;
    }).Respond(resp => GetHttpResponseMessage(HttpStatusCode.OK, requestVal?.PaymentIdentification?.EndToEndIdentification, BOA.PaymentStatus.ProcessingByBank, null, "TransId01"));


var request = PrepareRequest(GetCreateRequest("E2E1", 1, Enums.PaymentType.RTP, Enums.TransactionType.Credit));
var apiServiceMock = RestService.For<IRealTimePayment>("https://api.github.com", settings);
var result = await apiServiceMock.InitiatePaymentAsync(request, null).ConfigureAwait(false);```
于 2022-01-21T22:28:34.553 回答