简体   繁体   English

单元测试 - Flurl,如何模拟 flurl 请求响应?

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

Main service implementation using flurl使用 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使用 MS 测试的测试方法

 [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预期结果我想在调用主要服务方法时模拟请求和响应,但不幸的是我无法做到

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.每次调用RespondWith*都会向队列中添加一个新的虚假响应,因此在这里您将 2 个响应排队。 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.当在您的测试对象中进行 HTTP 调用时,Flurl 会将第一个调用出列并使用该响应伪造调用,因此您在响应正文中得到"OK" ,这显然不会 JSON 反序列化到您的ApplicationItemVm类型。 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. 200 是虚假响应的默认值,因此您甚至可以将其省略,除非您喜欢它以提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM