对于 .Net Core 3.1 WebApi 项目,我想在模拟外部调用的同时测试应用程序的完整管道(不是单元测试,完整测试)。该应用程序使用Refit SDK来注入(inject)SDK以供外部调用。我希望能够在此测试中覆盖 SDK,以便到达所有代码,但根据请求的内容返回动态响应。当我使用 richardszalay.mockhttp 进行测试时,如果它能满足我的需要,我非常愿意更换 mock 者。
我知道根据请求中的值我可以有不同的期望(我的示例中只有伪代码)。所以我能走到这一步。
但我需要的是,对于这个特定的工作流程,服务将在通过请求传入的响应中返回一个 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);
最佳答案
显然我只需要橡皮鸭就可以了。我能够通过这个代码片段实现我的目标,为下一个尝试解决这个问题的可怜的灵魂。
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);```
关于c# - 使用 Mock HttpClient 进行 Mock Refit SDK 注入(inject)以进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70807142/