[英]Why does unit test for Razor Page handler return type of PartialViewResult fail?
I am using Core 3.1 Xunit to test a Razor Page in an application, with Moq to mock any services.我正在使用 Core 3.1 Xunit 在应用程序中测试 Razor 页面,并使用 Moq 来模拟任何服务。 When running a test on a handler of
PageModel
to test if it returns PartialViewResult
type I get the following exception:在
PageModel
的处理程序上运行测试以测试它是否返回PartialViewResult
类型时,我得到以下异常:
System.NullReferenceException : Object reference not set to an instance of an object.
The PageModel
handler looks like this, with Application
as a property on PageModel
: PageModel
处理程序如下所示,其中Application
作为PageModel
上的一个属性:
public PartialViewResult OnGetApplicationAddedModalPartial()
{
return Partial("_ApplicationAddedModalPartial", Application);
}
And this is the failing test for it:这是它的失败测试:
[Fact]
public void OnGetApplicationAddedModalPartial_WhenCalled_ShouldReturPartialViewResultType()
{
//Arrange
_sut.Application = It.IsAny<ApplicationModel>();
//Act
var result = _sut.OnGetApplicationAddedModalPartial();
//Assert
Assert.IsType<PartialViewResult>(result);
}
What's curious is that I have another handler in that PageModel
that I successfully test to see if the return is of JasonResult
type.奇怪的是,我在该
PageModel
中有另一个处理程序,我成功测试了它以查看返回是否为JasonResult
类型。 Additionally, I have controllers in this application of which some actions also return a PartialViewResult
type that I successfully test for.此外,我在此应用程序中有一些控制器,其中一些操作还返回我成功测试的
PartialViewResult
类型。
What is special about a handler of return type PartialViewResult
on a PageModel
and how can I create a test to ensure that it returns PartialViewResult
? PageModel
上返回类型为PartialViewResult
的处理程序有什么特别之处,如何创建测试以确保它返回PartialViewResult
?
When testing a PartialViewResult
, you need to instantiate a number of properties of the PageModel
as part of your setup: https://github.com/dotnet/AspNetCore.Docs/issues/24312测试
PartialViewResult
时,您需要实例化PageModel
的许多属性作为设置的一部分: https://github.com/dotnet/AspNetCore.Docs/issues/24312
// Arrange
var httpContext = new DefaultHttpContext();
var modelState = new ModelStateDictionary();
var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
var modelMetadataProvider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary(modelMetadataProvider, modelState);
var tempData = new TempDataDictionary(httpContext, Mock.Of<ITempDataProvider>());
var pageContext = new PageContext(actionContext)
{
ViewData = viewData
};
var pageModel = new MyPageModel()
{
PageContext = pageContext,
TempData = tempData,
Url = new UrlHelper(actionContext),
MetadataProvider = modelMetadataProvider
};
// Act
var result = await pageModel.GetPartial();
// Assert
Assert.IsType<PartialViewResult>(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.