NSubstitute icon indicating copy to clipboard operation
NSubstitute copied to clipboard

Substiture for ILoggerFactory.CreateLogger<T>

Open alvipeo opened this issue 1 year ago • 2 comments

In almost any .NET project I need to have a substitute for ILoggerFactory and its probably most used method CreateLogger<T>(). It returns ILogger<T>, which is in turn:

public interface ILogger<out TCategoryName> : Microsoft.Extensions.Logging.ILogger

Any idea how could this be substituted?

alvipeo avatar Aug 25 '23 17:08 alvipeo

@alvipeo CreateLogger<T>() is an extension method so you need to substitute CreateLogger(string) (which is called from extension) instead:

var loggerFactory = Substitute.For<ILoggerFactory>();
loggerFactory.CreateLogger(null).ReturnsForAnyArgs(NullLogger<MyType>.Instance);

Or maybe just use NullLoggerFactory instead of mocking.

olegd-superoffice avatar Aug 29 '23 09:08 olegd-superoffice

In addition to @olegd-superoffice's suggestion on returning a substitute/NullLogger, there are some changes in #732 that may help with checking ILogger calls.

dtchepak avatar Sep 03 '23 09:09 dtchepak

related: https://github.com/nsubstitute/NSubstitute/issues/597

304NotModified avatar Apr 28 '24 22:04 304NotModified

@alvipeo Could you please close this issue if your question was answered?

olegd-superoffice avatar Apr 29 '24 06:04 olegd-superoffice

I think the question has been answered and therefore I will close this one.

Please let us know if you need further information or would like us to take another look at this

304NotModified avatar Apr 29 '24 11:04 304NotModified