简体   繁体   中英

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. 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

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

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

&& _.Headers == headers

Since using Linq-to-Mocks , the setup will need to be done differently

//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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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