'How to do unit testing of ViewData in razor pages?

Having the following reduced code (.net core 3.1):

public ActionResult OnGet()
{
    ViewData["ACustomMessage"] = $"This a custom message";

    return Page();
}

I need a unit test where I can test the message created in ViewData.

public void Test_ViewData()
{
    var loggerMock = new Mock<ILogger<PrivacyModel>>();
    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
    };
    PrivacyModel privacyRazorPage = new PrivacyModel(loggerMock.Object)
    {
        PageContext = pageContext,
        TempData = tempData,
        Url = new UrlHelper(actionContext)
    };

    var resultPrivacy = privacyRazorPage.OnGet();

    Assert.AreEqual("This a custom message", ((PageResult)resultPrivacy).ViewData["ACustomMessage"]);
}

This test does not work because resultPrivacy is returned as an instantiated object but with all its properties as null.

ViewData returned as null



Solution 1:[1]

You need change the following code:

Assert.AreEqual("This a custom message", ((PageResult)resultPrivacy).ViewData["ACustomMessage"]);

To:

Assert.AreEqual("This a custom message", privacyRazorPage.ViewData["ACustomMessage"]);

Whole working demo:

public void Test_ViewData()
{
    var loggerMock = new Mock<ILogger<PrivacyModel>>();
    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
    };
    PrivacyModel privacyRazorPage = new PrivacyModel(loggerMock.Object)
    {
        PageContext = pageContext,
        TempData = tempData,
        Url = new UrlHelper(actionContext)
    };
    privacyRazorPage.OnGet();
    Assert.AreEqual("This a custom message", privacyRazorPage.ViewData["ACustomMessage"]);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rena