I am using .NET Core. I want to pass value from query string parameter from unit test function to the azure function. I am facing issue with passing and accessing the query string parameter value.
The URL is https://localhost:4300/api/RolePageMapping?EnterpriseId=xyz
I want to use the query string parameter inside Azure function. The code is as below.
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
ILogger log)
{
string EnterpriseId = req.Query["EnterpriseId"];
}
I want to know how can I pass the value from my unit test function to Azure function?
[Fact]
public async Task Function_ReturnBadRequest()
{
var request = new Mock<HttpRequest>();
var logger = new MockLogger();
var actualResult = await
GetUserRolePageMapping.Run(request.Object, logger);
actualResult.Should().BeOfType<HttpResponseMessage>();
}
You would need to mock the HttpRequest.Query Property
of the HttpRequest
[Fact]
public async Task Function_ReturnBadRequest() {
//Arrange
var expectedValue = new StringValues("Hello World"); //Or what you want
var request = new Mock<HttpRequest>();
request
.Setup(_ => _.Query["EnterpriseId"])
.Returns(expectedValue);
var logger = new MockLogger();
//Act
var actualResult = await GetUserRolePageMapping.Run(request.Object, logger);
//Assert
actualResult.Should().BeOfType<HttpResponseMessage>();
}
To build more complex query strings we can use QueryCollection class. It's a little bit unconveniet beast but it has everything we need to build up query strings from values we have.
Building query string using QueryCollection class needs three steps:
Create instance of StringValues class. It's a class that takes either string or array of strings to its constructor. This class holds values for query string parameter.
Create Dictionary<string,StringValues> for query parameters. Add query parameter name and instance of StringValues to dictionary. Repeat it for all query parameters.
Create instance of QueryCollection and use dictionary as contructor argument.
[Fact] public async Task ViewPdf_returns_view_if_document_exists_and_html_was_asked()
{
var model = new ApplicationReviewModel(); var dictionary = new Dictionary<string, StringValues>(); dictionary.Add("showhtml", new StringValues("1")); dictionary.Add("showtoc", new StringValues("0")); _controller.Request.Query = new QueryCollection(dictionary); _applicationServiceMock.Setup(a => a.GetDocumentReview(It.IsAny<Guid>(), It.IsAny<string>())) .ReturnsAsync(() => model); var result = await _controller.ViewPdf(Guid.NewGuid()) as ViewResult; Assert.Same(model, result.Model); Assert.Equal("ApplicationPdf", result.ViewName);
}
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.