本文介绍了如何对ViewComponent.Invoke()进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ViewComponent
对象中,HttpContext
和User
是只读属性.
In ViewComponent
object, HttpContext
and User
are read-only properties.
如何对此类组件进行单元测试?
How to unit test such a component?
我正在使用MSTest Freamwork.
I'm using the MSTest Freamwork.
我的代码中使用了以下属性
The follow properties are used in my code
- 饼干
- 会话
- User(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
.这是模拟所需值的入口点.
According to source code the ViewComponent
relies on the ViewComponentContext.ViewContext
to expose those read only properties, Which in turn accesses the HttpContext
. That is your entry point to mock the desired values.
[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);
}
这篇关于如何对ViewComponent.Invoke()进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!