Mock the PageModel

This is to test whether local methods were called as part of a handler method. Such as ones that populate SelectList instances. Note: these methods should be marked public virtual in the actual PageModel so that they can be mocked.

Another note: you shouldn't test whether these methods were called. You should test to see if their side effects happened.

[Fact]
public async Task OnGetAsync_Calls_GetFlatplanDetailsAsync_And_GetOptionsAsync()
{
    // Arrange
    var mockHttpContext = new DefaultHttpContext();
    var cookies = new MockRequestCookieCollection(new Dictionary<string, string>());
    mockHttpContext.Request.Cookies = cookies;

    var indexModel = new Mock<IndexModel>(mockFlatplanService.Object, ...)
    {
        CallBase = true
    };
    indexModel.Object.HydratePageModel();
    indexModel.Object.PageContext.HttpContext = mockHttpContext;
    
    indexModel.Setup(m => m.GetFlatplanDetailsAsync()).Returns(Task.CompletedTask).Verifiable();
    indexModel.Setup(m => m.GetOptionsAsync()).Returns(Task.CompletedTask).Verifiable();
    // Act
    await indexModel.Object.OnGetAsync();

    // Assert
    indexModel.Verify(x => x.GetFlatplanDetailsAsync(), Times.Once());
    indexModel.Verify(x => x.GetOptionsAsync(), Times.Once());
}
Last updated: 7/24/2024 10:46:10 AM

On this page

Latest Updates

© 0 - 2025 - Mike Brind.
All rights reserved.
Contact me at Mike dot Brind at Outlook.com