2

For a .Net Core 3.1 WebApi project, I want to test the full pipeline of my application while mocking out the external calls (not a unit test, full test). This app uses Refit SDK to inject SDKs for external calls. I want to be able to override the SDK on this test so that all the code is reached but dynamic responses are returned depending on what the request was. While I am using richardszalay.mockhttp for testing, I'm more than willing to switch mockers if it gets me what I need.

I know I can have different expects depending on values inside the request (I have just psudo code in my example). So I can get this far.

What I need though, is that for this particular workflow, the service will return a ReferenceId value in the response that was passed in via the request. Any thoughts on how to dynamically create the ReferenceId field in the response when its based on the ReferenceId field in the request? Is it simply not possible?

 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);
Hope
  • 125
  • 9

1 Answers1

3

Apparently I just needed to rubber duck it. I was able to achieve my goals with this code snippet, for the next poor soul trying to solve this problem.

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);```
Hope
  • 125
  • 9