In ViewComponent
object, HttpContext
and User
are read-only properties.
How to unit test such a component?
I'm using the MSTest Freamwork.
The follow properties are used in my code
- Cookie
- Session
- 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);
}
Here is just a samle for async,
According to source code the
ViewComponent
relies on theViewComponentContext.ViewContext
to expose those read only properties, Which in turn accesses theHttpContext
. That is your entry point to mock the desired values.