简体   繁体   English

Azure Function C# 中的单元测试

[英]Unit Test in Azure Function C#

I want to unit test my azure function API by sending mock request and response data.我想通过发送模拟请求和响应数据来对我的天蓝色函数 API 进行单元测试。 But my test is getting failed even if i pass same Json data on both request and response.但是即使我在请求和响应中都传递了相同的 Json 数据,我的测试也会失败。 TestCode测试代码

  [TestMethod]
    public async Task ClinicReadTestMethod()
    {
        //Arrange

        //var clinicRequest = new
        //{
        //    Id = "1",
        //    OpenIdProvider = "Google",
        //    Subject = "Test",
        //    Name = "Test",
        //    Address = "Test",
        //    Email = "Test",
        //    Phone = "Test",
        //    Notes = "Test"
        //};
        var query = new Dictionary<string, StringValues>();
        query.Add("openIdProvider", "Google");
        query.Add("subject", "Test");
        
        //var body = JsonSerializer.Serialize(clinicRequest); 
        var logger = Mock.Of<ILogger>();
        var client = Mock.Of<CosmosClient>(); 
        ContentResultFactory contentResultFactory = new ContentResultFactory();

        //Act
        var testFunction = new ClinicReadFunction(contentResultFactory);
        var result = await testFunction.Run(TestFactory.HttpRequestSetup(query), client, logger); //fixme
        var resultObject = JsonSerializer.Serialize(result as ContentResult);

        //Assert
        var clinicResponse = new 
        {
            Id = "1",
            openIdProvider = "Google",
            subject = "Test",
            Name = "Test",
            Address = "Test",
            Email = "Test",
            Phone = "Test",
            Notes = "Test"
        };
        var resultBody = JsonSerializer.Serialize(clinicResponse);
        //var res = contentResultFactory.CreateContentResult(HttpStatusCode.OK);
        Assert.AreEqual(resultBody, resultObject);
    }


    }

This is how my azure function looks like.这就是我的天蓝色函数的样子。 It is taking two parameters and returning the response.它采用两个参数并返回响应。 I have tried to mock the data for unit test still no success.我试图模拟单元测试的数据仍然没有成功。 If anyone have idea how to unit test this azure function please let me know.如果有人知道如何对这个天蓝色函数进行单元测试,请告诉我。 //AzureFunction //Azure函数

 public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "")] HttpRequest req,
        [CosmosDB(
            databaseName: "",
            containerName: "",
            Connection = ""
            )] CosmosClient client,
        ILogger log)
    {
        string subject = req.Query["sub"];
        if (!Enum.TryParse(req.Query["idp"], out OpenIdProvider openIdProvider) || string.IsNullOrEmpty(subject))
        {
            var message = "";
            log.LogWarning();
            return _contentResultFactory.CreateContentResult(message, HttpStatusCode.BadRequest);
        }
        var query = client.GetContainer("", "").GetItemLinqQueryable<Clinic>()
            .Where(x => x.OpenIdProvider == openIdProvider && x.Subject == subject);
        Clinic clinic;
        using (var iterator = query.ToFeedIterator())
            clinic = (await iterator.ReadNextAsync()).FirstOrDefault();
        if (clinic == null)
        {
            log.LogWarning();
            return _contentResultFactory.CreateContentResult();
        }

        var response = new ClinicReadResponse(clinic);
        return _contentResultFactory.CreateContentResult(response, HttpStatusCode.OK);
    }

//TestFactory //测试工厂

  public static HttpRequest HttpRequestSetup(Dictionary<string, StringValues> query, string body)
    {
        var reqMock = new Mock<HttpRequest>();
        reqMock.Setup(req => req.Query).Returns(new QueryCollection(query));
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(body);
        writer.Flush();
        stream.Position = 0;
        reqMock.Setup(req => req.Body).Returns(stream);
        return reqMock.Object;
    }

    public static HttpRequest HttpRequestSetup(Dictionary<string, StringValues> query)
    {
        var reqMock = new Mock<HttpRequest>();
        reqMock.SetupGet(x => x.Query).Returns(new QueryCollection(query));
        return reqMock.Object;
    }

In both your Clinic objects, your are generating a new GUID for the ID by calling System.Guid.NewGuid.在您的两个诊所对象中,您正在通过调用 System.Guid.NewGuid 为 ID 生成一个新的 GUID。 Assuming the JSON generated from each object is the same shape (they will need to be if you want them to match), the values of each ID property will be different.假设从每个对象生成的 JSON 具有相同的形状(如果您希望它们匹配,则需要它们),每个 ID 属性的值将不同。 Since the IDs are different, your JSON strings are not equal, therefore causing the failure.由于 ID 不同,您的 JSON 字符串不相等,因此导致失败。

Here is a post that will show you how to manually create a Guid.这是一篇文章,将向您展示如何手动创建 Guid。 You can use this to ensure your IDs are of the same value when testing.您可以使用它来确保您的 ID 在测试时具有相同的值。 Assigning a GUID in C# 在 C# 中分配 GUID

I don't know what your Azure Function code looks like, but your test's setup to make an HTTP request tells me you're calling the method tied to the Http Trigger.我不知道您的 Azure 函数代码是什么样的,但是您发出 HTTP 请求的测试设置告诉我您正在调用与 Http 触发器相关的方法。 Consider the scope of what your method is doing;考虑你的方法的作用范围; if it is large (or is calling other methods), this will increase the chances of your test breaking as you change the Azure Function over time.如果它很大(或正在调用其他方法),随着时间的推移更改 Azure 函数,这将增加测试中断的机会。 To help future-proof your test make sure the method it's calling has a single responsibility.为了帮助您的测试适应未来,请确保它调用的方法具有单一职责。 This will make debugging your code easier to do if a change does make your test fail, and will lessen the likelihood of needing to edit your test to accommodate for code changes.如果更改确实使您的测试失败,这将使您的代码更容易调试,并且将减少需要编辑测试以适应代码更改的可能性。

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

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