Unit testing - Flurl , How to mock flurl request response?

4.6k Views Asked by At

Main service implementation using flurl

Public async Task<ApplicationItemVm> UpdateOpportunityInfo(string optyNumber, UpdateOpportunityVm model, string token = "")
    {
     
            var result = await "https://api.com/*"
                 .WithOAuthBearerToken(token)
                .PatchJsonAsync(model)
                .ReceiveJson<ApplicationItemVm>();
            return result;
   
    }

Test Method using MS Test

 [TestMethod]
    public async Task UpdateOppTest()
    {
       var updateOpportunityVm = new UpdateOpportunityVm
        {
            AboutYouIConfirm_c = true
        };

        var applicationItemVm = new ApplicationItemVm { AboutYouIConfirm_c=true};

        // fake & record all http calls in the test subject
        using (var httpTest = new HttpTest())
        {
            // arrange
            httpTest.
                RespondWith("OK", 200).RespondWithJson(applicationItemVm);
            // act
            var application = await applicationService.UpdateOpportunityInfo("optyNumber", updateOpportunityVm, "CloudToken");
            // assert
            httpTest.ShouldHaveCalled("https://api.com/*")
                .WithVerb(HttpMethod.Patch)
                .WithContentType("application/json");
        }

    }

   

After test method execution got following error

Response could nor deserilize

Let me know if I need to add more details.

Please suggest what's wrong I am doing.

Expected Result I want to mock request and response when I calling the main service method but unfortunately I not able to do

1

There are 1 best solutions below

1
On BEST ANSWER

I think the problem is the arrange step of your test:

httpTest.RespondWith("OK", 200).RespondWithJson(applicationItemVm);

Every call to RespondWith* will add a new fake response to the queue, so here you're enqueuing 2 responses. When the HTTP call is made in your test subject, Flurl will dequeue the first one and fake the call with that response, so you're getting "OK" back in the response body, which obviously won't JSON-desrialize to your ApplicationItemVm type. That's where the failure is occuring.

To fix this, just enqueue a single response in your arrange step:

httpTest.RespondWithJson(applicationItemVm, 200);

200 is the default for fake responses so you could even leave that out unless you like it there for readability.