问题
This is in ASP.net core 3.1, using XUnit and NSubstitute (Limited to these frameworks by business rules)
I have a ActionFilterAttribute derived model validation filter, (taken from this article: Validate the Model State Globally in .NET Core), that I need to unit test.
I'm having trouble getting the tests to work because I am getting null back regardless of what I try.
The test code below is based on this Stack Overflow post from 2017: How to unit test ActionFilterAttribute
The code I want to test:
public class ModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
My test
public class ModelStateAttributeTests
{
private readonly IFileCache _fileCache = new FileCache();
[Fact]
public void OnActionExecuting_ShouldNotBeNull()
{
//Arrange
var httpContext = new DefaultHttpContext();
var context = new ActionExecutingContext(
new ActionContext
{
HttpContext = httpContext,
RouteData = new RouteData(),
ActionDescriptor = new ActionDescriptor(),
},
new List<IFilterMetadata>(),
new Dictionary<string, object>(), new TestController(_fileCache));
var sut = new ModelStateAttribute();
//Act
sut.OnActionExecuting(context);
//Assert
context.Result.Should().NotBeNull();
}
}
Error message:
Test Name: AppName.Tests.Attributes.ModelStateAttributeTests.OnActionExecuting_ShouldNotBeNull
Test FullName: AppName.Tests.AppName.Tests.Attributes.ModelStateAttributeTests.AppName.Tests.Attributes.ModelStateAttributeTests.OnActionExecuting_ShouldNotBeNull
Test Source: C:\repos\AppName\AppName.Tests\Attributes\ModelStateAttributeTests.cs : line 20
Test Outcome: Failed
Test Duration: 0:00:00
Test Name: AppName.Tests.Attributes.ModelStateAttributeTests.OnActionExecuting_ShouldNotBeNull
Test Outcome: Failed
Result StackTrace:
at FluentAssertions.Execution.XUnit2TestFramework.Throw(String message)
at FluentAssertions.Execution.TestFrameworkProvider.Throw(String message)
at FluentAssertions.Execution.DefaultAssertionStrategy.HandleFailure(String message)
at FluentAssertions.Execution.AssertionScope.FailWith(Func`1 failReasonFunc)
at FluentAssertions.Execution.AssertionScope.FailWith(Func`1 failReasonFunc)
at FluentAssertions.Execution.AssertionScope.FailWith(String message, Object[] args)
at FluentAssertions.Primitives.ReferenceTypeAssertions`2.NotBeNull(String because, Object[] becauseArgs)
at AppName.Tests.Attributes.ModelStateAttributeTests.OnActionExecuting_ShouldNotBeNull()
Result Message: Expected object not to be <null>.
来源:https://stackoverflow.com/questions/60755839/how-to-unit-test-actionfilterattributes-onactionexecuting-with-xunit