Skip to content

Latest commit

 

History

History
71 lines (52 loc) · 2.06 KB

File metadata and controls

71 lines (52 loc) · 2.06 KB

Moq1004: ILogger should not be mocked

Item Value
Enabled True
Severity Warning
CodeFix False

Mocking ILogger or ILogger<T> is unnecessary and fragile. Use NullLogger.Instance (for ILogger) or NullLogger<T>.Instance (for ILogger<T>) for tests that ignore logging, or FakeLogger from Microsoft.Extensions.Diagnostics.Testing for tests that verify log output.

Examples of patterns that are flagged by this analyzer

using Microsoft.Extensions.Logging;

var mock = new Mock<ILogger>(); // Moq1004
var mock2 = new Mock<ILogger<MyService>>(); // Moq1004
var logger = Mock.Of<ILogger>(); // Moq1004
var logger2 = Mock.Of<ILogger<MyService>>(); // Moq1004

var repository = new MockRepository(MockBehavior.Strict);
var mock3 = repository.Create<ILogger>(); // Moq1004
var mock4 = repository.Create<ILogger<MyService>>(); // Moq1004

Solution

using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;

// For tests that ignore logging (non-generic ILogger)
ILogger logger = NullLogger.Instance;

// For tests that ignore logging (generic ILogger<T>)
ILogger<MyService> typedLogger = NullLogger<MyService>.Instance;
using Microsoft.Extensions.Diagnostics.Testing;

// For tests that verify log output
var fakeLogger = new FakeLogger<MyService>();

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable Moq1004
var mock = new Mock<ILogger<MyService>>(); // Moq1004
#pragma warning restore Moq1004

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.Moq1004.severity = none

For more information, see How to suppress code analysis warnings.