1

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

Yogesh Khurpe
  • 27
  • 3
  • 10
  • Could you post a stack trace with that exception? – Todd Menier May 08 '21 at 17:42
  • Hi Todd, I fixed null exception, The main issue is I am not able to mock request response of flurl when calling main method implementation. Expected Result:- I want to mock request and response when I calling the main service method but unfortunately I not able to do – Yogesh Khurpe May 09 '21 at 09:30
  • please let me know how can I setup mock for IFlurlRequest and IFlurlResponse? – Yogesh Khurpe May 09 '21 at 09:39

1 Answers1

5

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.

Todd Menier
  • 37,557
  • 17
  • 150
  • 173