Skip to content

Commit

Permalink
Enable classes derived from EnableQueryAttribute to unit test OnActio…
Browse files Browse the repository at this point in the history
…nExecuted in isolation (#776)
  • Loading branch information
KenitoInc authored Dec 20, 2022
1 parent 9cf8554 commit 4de92f5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ private ODataQueryOptions CreateAndValidateQueryOptions(HttpRequest request, ODa
{
RequestQueryData requestQueryData = request.HttpContext.Items[nameof(RequestQueryData)] as RequestQueryData;

if (requestQueryData.QueryValidationRunBeforeActionExecution)
if (requestQueryData != null && requestQueryData.QueryValidationRunBeforeActionExecution)
{
return requestQueryData.ProcessedQueryOptions;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,43 @@ private static IEnumerable<ControllerActionDescriptor> CreateDescriptors(string
return descriptors;
}

[Fact]
public void Derived_Class_Can_Unit_Test_When_OnActionExecuted_Is_Overridden()
{
// https://github.com/OData/AspNetCoreOData/issues/239: unit tests for derived classes fail because RequestQueryOptions missing from HttpContext.Items
IEdmModel model = new CustomersModelWithInheritance().Model;

var request = RequestFactory.Create("Get", "http://localhost/Customers?$filter=Id+eq+1", opt => opt.AddRouteComponents("odata", model, services => { }).Filter());

ODataUriParser parser = new ODataUriParser(model, new Uri("Customers", UriKind.Relative));
HttpContext httpContext = request.HttpContext;

Assert.NotNull(httpContext.RequestServices);

httpContext.Request.Method = "Get";
request.Configure("odata", model, parser.ParsePath());
ActionDescriptor actionDescriptor = CreateDescriptors("CustomersController", typeof(CustomersController))
.First(descriptor => descriptor.ActionName.StartsWith("Get", StringComparison.OrdinalIgnoreCase));
ActionContext actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor);

ActionExecutedContext context = new ActionExecutedContext(actionContext, new List<IFilterMetadata>(), new CustomersController());
context.Result = new ObjectResult(new List<Customer>() { new Customer { Id = 1, Name = "John Doe" } }) { StatusCode = 200 };

MyEnableQueryAttribute attribute = new MyEnableQueryAttribute();

// Act and Assert
ExceptionAssert.DoesNotThrow(() => attribute.OnActionExecuted(context));

}

private class MyEnableQueryAttribute : EnableQueryAttribute
{
public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}
}

#if NETCORE // Following functionality is only supported in NetCore.
[Fact]
public void OnActionExecuting_Throws_Null_Context()
Expand Down

0 comments on commit 4de92f5

Please sign in to comment.