Verifying the value of an argument passed to a method

In this example, I want to verify that the correct partial view was passed to the method that renders partials to strings. Here is the method:

public async Task<IActionResult> OnGetLedgerAsPdfAsync([FromServices] IPdfConverter pdfConverter)
{
    if (authService.Allows(User, To.PrintLedger))
    {
        var entries = await orderService.GetLedgerAsync(IssueId, OrderItemIds, At);
        entries = entries.Where(x => x.Confirmed).ToList();
        var html = await renderer.RenderPartialToStringAsync("/Pages/Ledger/_LedgerPdfPartial.cshtml", entries);
        var fileName = $"{entries.First().ProductName} {new DateTime(entries.First().Year, entries.First().Month, 1):MMM yyyy} Ledger.pdf";
        return File(pdfConverter.ToPortraitPdf(html, BaseHref), MediaTypeNames.Application.Pdf, fileName);
    }
    return Forbid();
}

Here is the test:

[Fact]
public async Task OnGetLedgerAsPdfAsync_ReturnsFileContentResult_ForAuthorisedUser()
{
    // Arrange
    authService.Setup(x => x.Allows(It.IsAny<ClaimsPrincipal>(), To.PrintLedger)).Returns(true);
    var ledgerEntries = new List<LedgerEntry> {
        new() { Confirmed = true, ProductName = "Test Product", Year = 2024, Month = 8 }
    };
    orderService.Setup(x => x.GetLedgerAsync(It.IsAny<int>(), It.IsAny<int[]>(), It.IsAny<DateTime?>())).ReturnsAsync(ledgerEntries);
        // Act
    var result = await indexModel.OnGetLedgerAsPdfAsync(Mock.Of<IPdfConverter>());

    // Assert
    Assert.IsType<FileContentResult>(result);
    orderService.Verify(x => x.GetLedgerAsync(It.IsAny<int>(),It.IsAny<int[]>(), It.IsAny<DateTime?>()), Times.Once);
    renderer.Verify(x => x.RenderPartialToStringAsync("/Pages/Ledger/_LedgerPdfPartial.cshtml", ledgerEntries, null), Times.Once);
    Assert.IsType<FileContentResult>(result);
    Assert.Equal(MediaTypeNames.Application.Pdf, ((FileContentResult)result).ContentType);
    Assert.Equal("Test Product Aug 2024 Ledger.pdf", ((FileContentResult)result).FileDownloadName);
}

So we verified that the order service was called with any values as arguments (using the It.IsAny placeholder), but we ensured that the renderer's RenderPartialToStringAsync method was called with specific argument values.

Last updated: 8/20/2024 3:28:02 PM

Latest Updates

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