jasontaylordev / CleanTesting

Sample code for the Clean Testing talk.
82 stars 26 forks source link

How to add ILogger<>? #3

Open alvipeo opened 4 years ago

alvipeo commented 4 years ago

Assuming I have this code:

        public static void RunBeforeAnyTests()
        {
            IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", true, true)
                .AddEnvironmentVariables();

            _configuration = builder.Build();

            ConnectionString = _configuration.GetConnectionString("DefaultConnection");

            ServiceCollection services = new ServiceCollection();

            Startup startup = new Startup(_configuration);

            services.AddSingleton(Mock.Of<IWebHostEnvironment>(w =>
                w.EnvironmentName == "Development" &&
                w.ApplicationName == "SomeProject"));

            startup.ConfigureServices(services);

            ScopeFactory = services.BuildServiceProvider().GetService<IServiceScopeFactory>();

            _checkpoint = new Checkpoint();
        }

How can I add ILogger here? Otherwise any command/query that require logger will fail. Thank you.

alvipeo commented 4 years ago

I kind of found it but I want to extend it.

Here's the NunitLogger I want to use:

    public class NunitLogger<T> : ILogger<T>, IDisposable
    {
        public NunitLogger()
        {
        }

        public void Dispose()
        {
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
            Func<TState, Exception, string> formatter)
        {
            TestContext.Out.WriteLine(state.ToString());
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return this;
        }
    }

    public class NunitLogger : ILogger, IDisposable
    {
        public NunitLogger()
        {
        }

        public void Dispose()
        {
        }

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
            Func<TState, Exception, string> formatter)
        {
            TestContext.Out.WriteLine(state.ToString());
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return this;
        }
    }

And now I need to make AddNunitLogging() extension method.

Bayonle commented 3 years ago

I"ve had luck with services.AddLogging();