I created a xUnit project to test this sample code
public class ClassToTest
{
private readonly ILogger<ClassToTest> _logger;
public ClassToTest(ILogger<ClassToTest> logger)
{
_logger = logger;
}
public void Foo() => _logger.LogError(string.Empty);
}
I installed Moq to create a mock instance for the logger
public class ClassToTestTests
{
private readonly ClassToTest _classToTest;
private readonly Mock<ILogger<ClassToTest>> _loggerMock;
public ClassToTestTests()
{
_loggerMock = new Mock<ILogger<ClassToTest>>();
_classToTest = new ClassToTest(_loggerMock.Object);
}
[Fact]
public void TestFoo()
{
_classToTest.Foo();
_loggerMock.Verify(logger => logger.LogError(It.IsAny<string>()), Times.Once);
}
}
When running the tests I get this error message
System.NotSupportedException: Unsupported expression: logger => logger.LogError(It.IsAny(), new[] { })
System.NotSupportedException Unsupported expression: logger => logger.LogError(It.IsAny(), new[] { }) Extension methods (here: LoggerExtensions.LogError) may not be used in setup / verification expressions.
After some research I know that all the log methods are just extension methods. Moq is not able to setup extension methods.
I would like to avoid installing additional third party packages for this problem. Are there any solutions to make the test pass?
ILogger
interface. You could check if that method is called instead. – Intuitionism