简体   繁体   English

如何对 razor 页面中的 ViewData 进行单元测试?

[英]How to do unit testing of ViewData in razor pages?

Having the following reduced code (.net core 3.1):具有以下简化代码(.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.我需要一个单元测试,我可以在其中测试在 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.此测试不起作用,因为resultPrivacy作为实例化的 object 返回,但其所有属性为 null。

ViewData 返回为 null

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"]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM