且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为azure函数v1编写单元测试

更新时间:2023-02-16 23:11:19

我不确定这是否是***的方法,但我确实想出了一些"只是"的东西。工作。我希望它至少可以帮助你开始

I'm not sure if this is the best way to do this but I did manage to come up with something that "just" worked. I hope it would at least help you to start off


using Microsoft.Azure.WebJobs.Host;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Text;

using UnitTestV1;

namespace UnitTestV1Test
{
    [TestClass]
    public class UnitTest1
    {
        protected TraceWriter log = new VerboseDiagnosticsTraceWriter();

        [TestMethod]
        public async void TestFunction1_Query()
        {
            var expected = "\"Hello Azure\""; // This seems to because the response is converted to valid JSON

            var res = await Function1.Run(CreateReq("http://localhost/func?name=Azure", ""), log);
            var actual = await res.Content.ReadAsStringAsync();

            Assert.AreEqual(expected, actual, "Failed!");
        }

        [TestMethod]
        public async void TestFunction1_Body()
        {
            var expected = "\"Hello Azure\""; // This seems to because the response is converted to valid JSON

            var res = await Function1.Run(CreateReq("", "{\"name\": \"Azure\"}"), log);
            var actual = await res.Content.ReadAsStringAsync();

            Assert.AreEqual(expected, actual, "Failed!");
        }

        public HttpRequestMessage CreateReq(string uri, string body)
        {
            var req = new HttpRequestMessage();
            req.SetConfiguration(new System.Web.Http.HttpConfiguration());

            if (!String.IsNullOrEmpty(uri))
            {
                req.RequestUri = new Uri(uri);
            }

            if (!String.IsNullOrEmpty(body))
            {
                req.Content = new StringContent(body, Encoding.UTF8, "application/json");
            }

            return req;
        }
    }

    public class VerboseDiagnosticsTraceWriter : TraceWriter
    {

        public VerboseDiagnosticsTraceWriter() : base(TraceLevel.Verbose)
        {

        }
        public override void Trace(TraceEvent traceEvent)
        {
            Debug.WriteLine(traceEvent.Message);
        }
    }
}