How to unit test ViewComponent.Invoke()?
Here is just a samle for async,
[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);
}
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);
}