Skip to content
This repository was archived by the owner on Dec 13, 2018. It is now read-only.
This repository was archived by the owner on Dec 13, 2018. It is now read-only.

Log[Severity] Extension Methods Make Unit Testing Logging Behavior Difficult #611

@ardalis

Description

@ardalis

Using extension methods rather than interface methods on ILogger makes it difficult to mock an ILogger effectively, which in turn makes unit testing logging behavior in classes that perform logging difficult.

Consider this controller code:

    public IActionResult GetImage(int id)
    {
        byte[] imageBytes;
        try
        {
            imageBytes = _imageService.GetImageBytesById(id);
        }
        catch (CatalogImageMissingException ex)
        {
            _logger.LogWarning($"No image found for id: {id}");
            return NotFound();
        }
        return File(imageBytes, "image/png");
    }

I want to write a unit test that confirms a warning message is logged when the exception is thrown. I can easily mock the service to throw the exception. But I can't mock the _logger.LogWarning call because it's an extension method:

    [Fact]
    public void LogsWarningGivenImageMissingException()
    {
        SetupMissingImage();
        _mockLogger.Setup(l => l.LogWarning(It.IsAny<string>()))
            .Verifiable();

        _controller.GetImage(_testImageId);

        _mockLogger.Verify();
    }

This code fails at runtime:

Message: System.NotSupportedException : Expression references a method that does not belong to the mocked object: l => l.LogWarning(It.IsAny(), new[] { })

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions