c# - 如果使用 CreateResponse 扩展方法返回 Azure Function HttpResponseMessage,则执行测试时出错

标签 c# unit-testing azure visual-studio-2017 azure-functions

我的Azure函数代码如下

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);

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

**

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 模板的代码) 并返回如下响应,我在测试方法中得到响应,并且测试用例运行良好。

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

关于c# - 如果使用 CreateResponse 扩展方法返回 Azure Function HttpResponseMessage,则执行测试时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44447232/

相关文章:

C#、Unity - 单个函数采用多个不同的对象

c# - BinaryFormatter 和 Filestream 的关系

angularjs - $httpBackend.flush() 方法抛出错误 : [$rootScope:infdig] 10 $digest() iterations reached. 中止

Python如何断言一个方法已被调用

azure - 从VM内部如何识别它是AWS机器还是Azure机器?

azure - 当资源在主位置不可用时,如何在 Azure 资源管理器模板的辅助位置部署资源?

azure - 时间序列的注意事项

c# - 使用 Lambda 或 Linq 为 MVC5 中的 Razor View 创建带有所选项目的 SelectList 模型

javascript - 如何在 Azure Build Pipeline 中打包 JS 应用程序并保存在单独的 C# 存储库中

unit-testing - 我们应该使用单元测试框架测试打印在控制台/命令提示符上的文本吗?