简体   繁体   中英

Unit Test in Azure Function C#

I want to unit test my azure function API by sending mock request and response data. But my test is getting failed even if i pass same Json data on both request and response. 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

 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. 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. Since the IDs are different, your JSON strings are not equal, therefore causing the failure.

Here is a post that will show you how to manually create a Guid. You can use this to ensure your IDs are of the same value when testing. Assigning a GUID in C#

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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