Home > Back-end >  How to return Partial from Razor Page when called from Xunit without getting System.NullReferenceExc
How to return Partial from Razor Page when called from Xunit without getting System.NullReferenceExc

Time:08-24

Getting a 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.

Razor Page:

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:

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:

<h1>Test</h1>

The Partial loads perfectly fine when running the RazorPage Project (i.e. SomeProject.Pages) and hitting the endpoint directly, the Razor Page server encounters no exceptions and serves the partial just fine to the user. Only when running it from Xunit does the aforementioned System.NullReferenceException appear.

System.NullReferenceException when returning Partial

How am I meant to test if a Razor Page Partial loads correctly without getting a NullReferenceException?

CodePudding user response:

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

  • Related