[英]How to return Partial from Razor Page when called from Xunit without getting System.NullReferenceException
Getting a System.NullReferenceException: 'Object reference not set to an instance of an object.'
获取
System.NullReferenceException: 'Object reference not set to an instance of an object.'
when attempting to return a Partial from a Razor Page handler that's being invoked from an Xunit test method.当尝试从 Xunit 测试方法调用的 Razor 页面处理程序返回 Partial 时。
Razor Page: Razor 页:
namespace SomeProject.Pages
{
public class IndexModel : PageModel
{
public async Task<IActionResult> OnGetAsync()
{
return Page();
}
public async Task<PartialViewResult> OnGetTest()
{
return Partial("Modals/_Test");
}
}
}
Xunit class in a different project: Xunit class 在不同的项目中:
using SomeProject.Pages;
using Xunit;
namespace SomeProject.Pages.Tests.Xunit
{
public class IndexUnitTests
{
[Fact]
public async Task OnGetTest_ReturnsPartial()
{
IndexModel pageModel = new IndexModel();
IActionResult? result = await pageModel.OnGetTest();
Assert.NotNull(result);
Assert.IsType<PartialViewResult>(result);
}
}
}
Partial located at Views/Shared/Modals/_Test.cshtml
:部分位于
Views/Shared/Modals/_Test.cshtml
:
<h1>Test</h1>
The Partial loads perfectly fine when running the RazorPage Project (ie SomeProject.Pages
) and hitting the endpoint directly, the Razor Page server encounters no exceptions and serves the partial just fine to the user.当运行 RazorPage 项目(即
SomeProject.Pages
)并直接点击端点时,部分加载非常好,Razor 页面服务器没有遇到任何异常,并且为用户提供了部分。 Only when running it from Xunit does the aforementioned System.NullReferenceException
appear.只有从 Xunit 运行它时,才会出现前面提到的
System.NullReferenceException
。
How am I meant to test if a Razor Page Partial loads correctly without getting a NullReferenceException?我如何测试 Razor 页面部分是否正确加载而没有得到 NullReferenceException?
You need modify your unit test code like below:您需要修改单元测试代码,如下所示:
[Fact]
public async Task OnGetTest_ReturnsPartial()
{
var modelMetadataProvider = new EmptyModelMetadataProvider();
var viewData = new ViewDataDictionary(modelMetadataProvider, new ModelStateDictionary());
var pageModel = new IndexModel
{
PageContext = new PageContext
{
ViewData = viewData
},
MetadataProvider = modelMetadataProvider,
};
var result = await pageModel.OnGetTest();
Assert.NotNull(result);
Assert.IsType<PartialViewResult>(result);
}
Reference:参考:
https://github.com/dotnet/aspnetcore/blob/c85baf8db0c72ae8e68643029d514b2e737c9fae/src/Mvc/Mvc.RazorPages/test/PageModelTest.cs#L1922 https://github.com/dotnet/aspnetcore/blob/c85baf8db0c72ae8e68643029d514b2e737c9fae/src/Mvc/Mvc.RazorPages/test/PageModelTest.cs#L1922
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.