如何对 ViewComponent.Invoke() 进行单元测试?

How to unit test ViewComponent.Invoke()?

ViewComponent对象中,HttpContextUser是只读属性。

如何对这样的组件进行单元测试?

我正在使用 MSTest Freamwork。

我的代码中使用了以下属性

  1. Cookie
  2. 会话
  3. 用户(System.Security.Principal)

public ViewViewComponentResult Invoke()
{
    var vm = new SummaryViewModel();
    if (User.Identity is ClaimsIdentity identity && identity.IsAuthenticated)
    {
        vm.IsAuthenticated = true;
        vm.UserName = identity.Claims.FirstOrDefault(c => c.Type == "UserName").Value;
        vm.PhotoUrl = identity.Claims.FirstOrDefault(c => c.Type == "FacePicture").Value;
    }
    return View(vm);
}

[TestMethod]
public void UserSummaryVcTest()
{
    var component = new UserSummaryViewComponent();
    var model = component.Invoke().ViewData.Model as SummaryViewModel;
    Assert.AreEqual("UserName", model.UserName);
} 

根据源代码,ViewComponent 依赖于 ViewComponentContext.ViewContext 公开那些只读属性,这些只读属性又访问 HttpContext。这是模拟所需值的切入点。

[TestMethod]
public void UserSummaryVcTest() {

    // Arrange
    var expected = "Username value";
    var httpContext = new DefaultHttpContext(); //You can also Mock this
    //...then set user and other required properties on the httpContext as needed

    var viewContext = new ViewContext();
    viewContext.HttpContext = httpContext;
    var viewComponentContext = new ViewComponentContext();
    viewComponentContext.ViewContext = viewContext;

    var viewComponent = new UserSummaryViewComponent();
    viewComponent.ViewComponentContext = viewComponentContext;

    //Act
    var model = viewComponent.Invoke().ViewData.Model as SummaryViewModel;

    //Assert
    Assert.AreEqual(expected, model.UserName);
} 

这里只是一个异步示例,

    [TestMethod]
        public async System.Threading.Tasks.Task InvokeAsyncNameAsync()
{
# setup mocks
...
var httpContext = new DefaultHttpContext();
            var viewContext = new ViewContext();
            viewContext.HttpContext = httpContext;
            var viewComponentContext = new ViewComponentContext();
            viewComponentContext.ViewContext = viewContext;

            var footerComponent = CreateComponentInstance();
            footerComponent.ViewComponentContext = viewComponentContext;

            ViewViewComponentResult result = await footerComponent.InvokeAsync() as ViewViewComponentResult;
            FooterModel resultModel = (FooterModel)result.ViewData.Model;

....
# do your asserts verifications

            Assert.AreEqual(expectedTest, resultModel.FooterText);
}