【发布时间】:2019-11-15 23:18:30
【问题描述】:
我目前正在按照本指南 (https://docs.microsoft.com/en-us/azure/azure-functions/functions-test-a-function) 向我的 Azure Functions 应用程序添加测试。
目前我已经构建了 8 个运行良好的 Azure Functions,我还添加了一个 Functions.Tests 项目并在其中引用了 Azure Functions 项目。
这是 Functions.Tests 当前的样子。
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Xunit;
namespace Functions.Tests
{
public class FunctionsTests
{
private readonly ILogger logger = TestFactory.CreateLogger();
[Fact]
public async void Http_trigger_should_return_known_string()
{
var request = TestFactory.CreateHttpRequest("name", "Bill");
var response = (OkObjectResult)await HttpFunction.Run(request, logger);
Assert.Equal("Hello, Bill", response.Value);
}
[Theory]
[MemberData(nameof(TestFactory.Data), MemberType = typeof(TestFactory))]
public async void Http_trigger_should_return_known_string_from_member_data(string queryStringKey, string queryStringValue)
{
var request = TestFactory.CreateHttpRequest(queryStringKey, queryStringValue);
var response = (OkObjectResult)await HttpFunction.Run(request, logger);
Assert.Equal($"Hello, {queryStringValue}", response.Value);
}
[Fact]
public void Timer_should_log_message()
{
var logger = (ListLogger)TestFactory.CreateLogger(LoggerTypes.List);
TimerTrigger.Run(null, logger);
var msg = logger.Logs[0];
Assert.Contains("C# Timer trigger function executed at", msg);
}
}
}
但是我在 FunctionsTests.cs 中收到以下错误
我已经尝试了 Visual Studio 中的所有建议修复程序并在线检查了资源,但没有运气。也许我缺少参考?我不确定,因为我已经逐字逐句地遵循了指南。
使用的示例 Azure 函数:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Exemplar
{
public static class getCase
{
[FunctionName("getCase")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/case/caseId")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
}
}
【问题讨论】:
-
HttpFunction和TimerTrigger在这种情况下是正在测试的 Azure 函数。名称或您的功能类是什么?那是你应该使用的。还要避免使用async void重构这些测试以使用async Task -
@Nkosi 我有一个名为 Examples 的 c# 项目,其中包含多个函数,例如 getEntity。在这种情况下,HttpFunction 会更改为 Examples.getEntity.Run 吗?
-
是的,就是这样。 edit 将其中一项功能放入问题中,以便我们向您展示如何测试它。它们是静态函数还是实例函数?
-
@Nkosi 已尝试用我的应用程序中的相关函数替换 HttpFunction,但是 VS 只会识别项目“Exemplar”而不是其中的 azurefunctions。
-
@Nkosi 能够成功地将 TimerTrigger 替换为 Exemplar.getCase.Run,但是 HttpFunction 不接受类似的替换
标签: c# azure unit-testing testing azure-functions