将自定义筛选器属性单元测试从.NET Framework迁移到.NET Core 2.1



我有一个.NET Framework 4.7.2 MVC应用程序,正在迁移到.NET Core 2.1应用程序。到目前为止,一切都在工作,但我无法获得一个单元测试,它正在测试我在.NET核心版本中编写的自定义属性。

这是框架版本中属性测试的代码

private HttpActionContext _successContext;
private HttpActionContext _failContext;
private HttpControllerContext _controllerContext;
[TestInitialize]
public void Initialize()
{
_controllerContext = new HttpControllerContext
{
Request = new HttpRequestMessage(HttpMethod.Post, string.Empty)
{
Content = new ObjectContent(typeof(string), string.Empty, new JsonMediaTypeFormatter())
}
};
_successContext = new HttpActionContext {ControllerContext = _controllerContext};
_successContext.ModelState.Add("TestField", new ModelState());
_failContext = new HttpActionContext { ControllerContext = _controllerContext };
_failContext.ModelState.Add("TestField", new ModelState());
_failContext.ModelState.AddModelError("TestField", "Test error message");
}

在.NET Core版本中新建HttpControllerContext和ActionContext的正确方法是什么?

或者这是在.NET Core中测试属性的错误方法?

这是正在测试的属性的Frameowrk版本

public class JsonValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid) return;
var errorMessages = actionContext.ModelState.Values
.SelectMany(modelState => modelState.Errors.Select(x => x.ErrorMessage));
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, Json.Encode(errorMessages));
}
}

这就是我在.NET Core版本中开发该属性的方式(它按预期工作,但我只需要重新实现它的单元测试

public class JsonValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
if (actionContext.ModelState.IsValid) return;
IEnumerable<string> errorMessages = actionContext.ModelState.Values.SelectMany(modelState => modelState.Errors.Select(x => x.ErrorMessage));
actionContext.Result = new BadRequestObjectResult(errorMessages);
}
}

给定属性的.Net Core版本,您实际需要的是属性测试的ActionExecutingContext

例如

// Arrange
var context = new ActionExecutingContext(
new ActionContext
{
HttpContext = new DefaultHttpContext(),
RouteData = new RouteData(),
ActionDescriptor = new ActionDescriptor()
},
new List<IFilterMetadata>(),
new Dictionary<string, object>(),
new object());
context.ModelState.AddModelError("TestField", "Test error message");
var filter = new JsonValidationFilterAttribute();
// Act
filter.OnActionExecuting(context);
// Assert
Assert.IsInstanceOfType(context.Result, typeof(BadRequestObjectResult));
//context.Result.Should().BeOfType<BadRequestObjectResult>(); Fluent Assertions