执行测试时出错,如果对 return Azure Function HttpResponseMessage 使用 CreateResponse 扩展方法

Error while executing test, if using CreateResponse extention method to return Azure Function HttpResonseMessage

我的 Azure Function 代码如下

public static class MyHttpTriggerFunction
{       
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
    {
        // some business logic

        if (valid)
        {
            return req.CreateResponse(HttpStatusCode.OK, true);
        }
        else
        {
             return req.CreateResponse(HttpStatusCode.BadRequest, "some error message");
        }            
    }
}

在我的测试项目中,我正在读取如下结果:

var result = await MyHttpTriggerFunction.Run(req, log).ConfigureAwait(false);

执行函数后,当它尝试return结果变量中的响应时,测试方法失败并出现异常。

**

System.InvalidOperationException: The request does not have an associated configuration object or the provided configuration was null.

**

我已确保测试项目具有相同的 System.Net.Http.HttpRequestMessageExtension dll。

如果我更改函数代码不使用CreateResponse扩展方法(此扩展方法来自VS 2017模板的代码) return 如下所示的响应,我在测试方法中得到响应并且测试用例运行正常。

var res = new HttpResponseMessage();
if (valid)
{
    res.StatusCode = HttpStatusCode.OK;
    res.Content = new ObjectContent<bool>(true, new JsonMediaTypeFormatter());        
    return res;
}
else
{
     res.StatusCode = HttpStatusCode.BadRequest;
     res.Content = new ObjectContent<string>("some error message", new JsonMediaTypeFormatter());
     return res;
}

下面是错误的堆栈跟踪

Result StackTrace: at System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage request, HttpStatusCode statusCode, T value, HttpConfiguration configuration) at System.Net.Http.HttpRequestMessageExtensions.CreateResponse[T](HttpRequestMessage request, HttpStatusCode statusCode, T value) at MyFunctionApp.MyHttpTriggerFunction.d__1.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.d__2.MoveNext() in C:\Users\rsingh\Desktop\Git_Workspace\ActivationAPI\MyFunctionAppUnitTest\MyHttpTriggerFunctionTest.cs:line 53 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.ThreadOperations.ExecuteWithAbortSafety(Action action) Result Message: Test method MyFunctionAppUnitTest.MyHttpTriggerFunctionTest.MyHttpTriggerFunction_SuccessResult threw exception: System.InvalidOperationException: The request does not have an associated configuration object or the provided configuration was null.

我是不是遗漏了一些微不足道的东西

错误消息告诉您问题所在。

The request does not have an associated configuration object or the provided configuration was null.

在 httpserver 之外测试请求时,您需要给请求一个 HttpConfiguration.

// Arrange.
var configuration = new HttpConfiguration();
var request = new System.Net.Http.HttpRequestMessage();
request.Properties[System.Web.Http.Hosting.HttpPropertyKeys.HttpConfigurationKey] = configuration;

//...other code

这并非特定于 Azure Functions,但为了在实际 HTTP 请求的上下文之外执行此测试,您需要确保创建一个 HttpConfiguartion 实例,并根据需要对其进行配置(例如添加您可能需要的任何格式化程序)并使用该对象在 HttpRequestMessage 实例上调用 SetConfiguration

示例:

var configuration = new HttpConfiguration();
var request = new HttpRequestMessage();
request.SetConfiguration(configuration);