如何unit testingViewComponent.Invoke()?
在ViewComponent
对象中, HttpContext
和User
是只读属性。
如何对这样的组件进行unit testing?
我正在使用MSTest Freamwork。
以下属性用于我的代码中
- 曲奇饼
- 会议
- 用户(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 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("UserName", model.UserName); }
- asp.net核心中的TempData null
- 中间件中的HttpContext .NET核心保存实例
- ASP.NET 5(核心):如何在会话缓存(ISession)中存储对象?
- 控制器错误“Microsoft.AspNetCore.Mvc.Rendering.SelectListItem”中的MVC Core SelectList下拉列表
- 正则表达式默认ASP.NET核心标识密码
- validationGoogle Id令牌
- 如何在ASP.NET Core Identity中注销其他用户
- ASP.NET核心中的dependency injection
- HttpClient.GetAsync永远不会在Xamarin.Android上返回