Why doesn't [FromQuery] work when unit testing a Razor page?

68 Views Asked by At

I have this property in a PageModel:

[FromQuery(Name = "paypalPlanId")] public string? paypalPlanId { get; set; }

It works when calling the page within the application - the property is set to the value of the querystring parameter.

When I call it from a unit test using a mocked HttpContext, with a mocked HttpRequest containing the the same querystring, it does not work - the property is null.

This shows the correct value when running the app

This shows it is null when running the test

Here is the calling part of the unit test:

// arrange
queryParameters.Add(Tuple.Create("paypalPlanId", "TESTPLAN1"));
var config = CoachWorkbench.Test.TestHelpers.TestHelperConfiguration.GetConfiguration();
HttpContext httpContext = CommonTestHttpContext();
PlanEditModel page = new PlanEditModel(config);
page.AddPageModelContextExtension(httpContext, errorList);

// Act
IActionResult result = await page.OnGetAsync();

I have hundreds of other unit tests using the same mocked HttpContext & HttpRequest code and they work fine. Testing specifically for the correct QueryString also works fine. I was expecting the [FromQuery] field to be populated with the query value.

I am assuming that either a) the [FromQuery] functionality uses some HttpRequest component that I am unaware of and have not mocked or b) the [FromQuery] functionality uses some middleware functionality that I am unaware of and that is bypassed by the unit test.

0

There are 0 best solutions below