Azure函数 v4 单元测试

huangapple go评论64阅读模式
英文:

Azure function v4 unit tests

问题

这是一个生成的函数示例,我该如何测试Azure函数?

    public static class Test
    {
        [Function("Test")]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger("BLEbLE");
            logger.LogInformation("C# HTTP触发器函数正在处理请求。");

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("欢迎使用Azure函数!");

            return response;
        }
    }

我已生成方法并尝试使用xunit进行测试,但我不知道如何模拟HttpRequestData、FunctionContext和HttpResponseData,这些都是抽象类,所以我应该为它们创建自定义类并继承这三个类,还是有其他方法可以测试它呢?

英文:

How can i test azure function this is an example generated function:

public static class Test
{
    [Function("Test")]
    public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
        FunctionContext executionContext)
    {
        var logger = executionContext.GetLogger("BLEbLE");
        logger.LogInformation("C# HTTP trigger function processed a request.");

        var response = req.CreateResponse(HttpStatusCode.OK);
        response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

        response.WriteString("Welcome to Azure Functions!");

        return response;
    }
}

i have generated method and i tried testing it with xunit but i don't how to mock HttpRequestData , FunctionContext and HttpResponseData, these are abstract classes so should i create custom classes for them and inherit for this 3 or maybe there is other way to test it?

答案1

得分: 2

以下是您要翻译的代码部分:

//Arrange
var context = Substitute.For<FunctionContext>();
var request = Substitute.For<HttpRequestData>(context);
var response = Substitute.For<HttpResponseData>(context);

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(Options.Create(new WorkerOptions{Serializer = new JsonObjectSerializer()}));

var serviceProvider = serviceCollection.BuildServiceProvider();
context.InstanceServices.ReturnsForAnyArgs(serviceProvider);

request.Headers.ReturnsForAnyArgs(new HttpHeadersCollection());
response.Headers.ReturnsForAnyArgs(new HttpHeadersCollection());
response.Body.ReturnsForAnyArgs(new MemoryStream());
request.CreateResponse().ReturnsForAnyArgs(response);

var function = new Function();

//Act
var result = await function.Run(request);
result.Body.Position = 0;
var content = await JsonSerializer.DeserializeAsync<ErrorResponse>(result.Body);

//Assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal("Error", content?.Message);

希望这能帮助您。

英文:

Tried with the below code snippet:

//Arrange
var context = Substitute.For&lt;FunctionContext&gt;();
var request = Substitute.For&lt;HttpRequestData&gt;(context);
var response = Substitute.For&lt;HttpResponseData&gt;(context);

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(Options.Create(new WorkerOptions{Serializer = new JsonObjectSerializer()}));

var serviceProvider = serviceCollection.BuildServiceProvider();
context.InstanceServices.ReturnsForAnyArgs(serviceProvider);

request.Headers.ReturnsForAnyArgs(new HttpHeadersCollection());
response.Headers.ReturnsForAnyArgs(new HttpHeadersCollection());
response.Body.ReturnsForAnyArgs(new MemoryStream());
request.CreateResponse().ReturnsForAnyArgs(response);

var function = new Function();

//Act
var result = await function.Run(request);
result.Body.Position = 0;
var content = await JsonSerializer.DeserializeAsync&lt;ErrorResponse&gt;(result.Body);

//Assert
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Equal(&quot;Error&quot;, content?.Message);

There is a documentation on migrating the Azure Functions in-process to Isolated worker process but no information on implementing the Tests like Unit, Integration Tests.

Microsoft Azure Team has taken this implementation of complete test framework for the isolated-workers process as a priority item #281 and given the above code snippet for the temporary workaround.

huangapple
  • 本文由 发表于 2023年3月7日 21:09:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75662400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定