Mocking Service That Returns Sample Data

Sometimes, a service in a method returns data that other parts of the method depend on. This might happen when a page handler populates a SelectList. If the SelectList is not provided with data, an ArgumentNullException might be thrown. In this case, mock the service to return test data instead.

Here's a Page Handler that calls into the OrderItemTypeService to populate OrderItemTypeOptions - an instance of SelectList:

public async Task<IActionResult> OnGetManageAdvertisementContentAsync(int advertid)
{
    if (authorisationService.Allows(User, To.EditAdvertisement))
    {
        OrderItem = await orderItemService.FindByIdAsync(advertid);
        OrderItemTypeOptions = new SelectList(await orderItemTypeService.OrderItemTypesAsync(), nameof(OrderItemType.OrderItemTypeId), nameof(OrderItemType.Name), null, "OrderItemCategory.Name");
        return Partial("_EditAdvertisement", this);
    }
    return Forbid();
}

And here's sample List<OrderItemType> data being generated and the mock service being set up to return it from the relevant method call:

[Fact]
public async Task OnGetManageAdvertisementContentAsync_ReturnsPartialView_ForAuthorisedUser()
{
    // Arrange
    var indexModel = new IndexModel(mockFlatplanService.Object, mockOrderItemService.Object, mockEditorialService.Object, mockProductService.Object, mockIssueService.Object, mockOrderItemTypeService.Object, mockAuthorisationService.Object);
    indexModel.HydratePageModel(user);
    mockAuthorisationService.Setup(x => x.Allows(It.IsAny<ClaimsPrincipal>(), To.EditAdvertisement)).Returns(true);
    var orderItemTypes = new List<OrderItemType>
    {
        new OrderItemType { OrderItemTypeId = 1, Name = "Type1", OrderItemCategory = new OrderItemCategory { Name = "Category1" } },
        new OrderItemType { OrderItemTypeId = 2, Name = "Type2", OrderItemCategory = new OrderItemCategory { Name = "Category2" } }
    };

    mockOrderItemTypeService.Setup(x => x.OrderItemTypesAsync()).ReturnsAsync(orderItemTypes);
    mockOrderItemService.Setup(x => x.FindByIdAsync(It.IsAny<int>())).ReturnsAsync(new OrderItem { OrderItemId = 1 });

    // Act
    var result = await indexModel.OnGetManageAdvertisementContentAsync(1);

    // Assert
    Assert.IsType<PartialViewResult>(result);
}
Last updated: 7/25/2024 2:17:39 PM

Latest Updates

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