简体   繁体   English

如何在 Azure Function 的模拟测试中为 HttpRequest 添加自定义 header 和不记名令牌

[英]How to add custom header and bearer token for HttpRequest in Mock Test for Azure Function

I am writing Unit Test for Function App which accept HttpRequest and run the secured api call with query parameters and some custom Headers and Bearer Token.我正在为 Function 应用程序编写单元测试,该应用程序接受 HttpRequest 并使用查询参数和一些自定义标头和承载令牌运行安全的 api 调用。 I able to pass the query to request But how to add Headers is not working.我能够将查询传递给请求但是如何添加标题不起作用。

I have tried the following code, edited my code as per suggestion of @Nkosi我尝试了以下代码,根据@Nkosi 的建议编辑了我的代码

var postParam = new Dictionary<string, StringValues>();
postParam.Add("param1", "123");
request.Query = new QueryCollection(postParam);

var headers = new HttpClient().DefaultRequestHeaders;
headers.Add("Transaction", "1234");
var request = Mock.Of<HttpRequest>(_ =>
            _.Query == query && _.Headers == headers //<-- setup desired members
        );
var logger = Mock.Of<ILogger>();

var response = azureFunction.Run(request, logger);

Calling the following function调用如下 function

public static HttpResponseMessage Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
        ILogger log){
}

I am getting error here operater == can not be applied to IHeaderDictionary and HttpRequestHeaders我在这里遇到错误 operator == can't be applied to IHeaderDictionary 和 HttpRequestHeaders

&& _.Headers == headers

Since using Linq-to-Mocks , the setup will need to be done differently由于使用Linq-to-Mocks ,因此需要以不同方式完成设置

//Arrange
var postParam = new Dictionary<string, StringValues>();
postParam.Add("param1", "123");
var query = new QueryCollection(postParam);

var headers = new HttpRequestHeaders();
headers.Add("Transaction", "1234");

var request = Mock.Of<HttpRequest>(_ => 
    _.Query == query && _.Headers == headers //<-- setup desired members
);
var logger = Mock.Of<ILogger>();

//Act
var response = azureFunction.Run(request, logger);

//...

You could also mock the IHeaderDictionary instead您也可以改为模拟IHeaderDictionary

//Arrange
var postParam = new Dictionary<string, StringValues>();
postParam.Add("param1", "123");
var query = new QueryCollection(postParam);

//mock header dictionary
var headers = Mock.Of<IHeaderDictionary>(_ =>
    _["Transaction"] == "1234"
);

var request = Mock.Of<HttpRequest>(_ => 
    _.Query == query && _.Headers == headers //<-- setup desired members
);
var logger = Mock.Of<ILogger>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM